AnyCompiler

Interfaces

An interface defines a set of methods a type must have. Unlike many languages, Go has no "implements" keyword at all — a type satisfies an interface automatically, just by having methods with matching names and signatures. This is called implicit (or structural) interface satisfaction.

package main

import "fmt"

type Shape interface {
	Area() float64
}

type Circle struct {
	Radius float64
}

func (c Circle) Area() float64 {
	return 3.14159 * c.Radius * c.Radius
}

func describe(s Shape) {
	fmt.Printf("Area: %.2f\n", s.Area())
}

func main() {
	describe(Circle{Radius: 2})
}
Output
Area: 12.57

What a real missing-method error looks like

Because satisfaction is checked structurally, passing a type that's missing a required method is caught immediately at compile time. This is genuinely what the compiler reports — captured from a real run, not written to look plausible:

package main

import "fmt"

type Shape interface {
	Area() float64
}

type Triangle struct {
	Base, Height float64
}

func describe(s Shape) {
	fmt.Printf("Area: %.2f\n", s.Area())
}

func main() {
	describe(Triangle{Base: 4, Height: 3})
}
Output
# command-line-arguments
./main.go:18:19: cannot use Triangle literal (type Triangle) as type Shape in argument to describe:
	Triangle does not implement Shape (missing Area method)

Triangle never defined an Area() method, so it simply doesn't satisfy Shape — there's no explicit declaration to fix, because there was never one to begin with. Add the missing method, and the exact same Triangle value would satisfy Shape without any other change.

Next: pointers — & and *, more direct than Rust's ownership model.

Practice exercise

Define an interface Named with a method Name() string. Define a struct Dog { DogName string } with a Name() method returning d.DogName. Write a function greet(n Named) that prints "Hello, " + n.Name(). Call greet with a Dog{DogName: "Rex"}.