Interfaces let us write flexible code by defining what methods a type must have. Interface satisfaction means a type has all methods an interface needs, so it can be used wherever that interface is expected.
Interface satisfaction in Go
type InterfaceName interface { Method1(params) returnType Method2(params) returnType } // A type satisfies an interface if it has all methods listed in the interface. type MyType struct {} func (m MyType) Method1(params) returnType { // implementation } func (m MyType) Method2(params) returnType { // implementation }
In Go, you don't explicitly declare that a type implements an interface. It happens automatically if the type has all required methods.
This is called 'implicit interface satisfaction' and helps keep code simple and flexible.
Dog satisfies the Speaker interface because it has the Speak method.type Speaker interface { Speak() string } type Dog struct {} func (d Dog) Speak() string { return "Woof!" }
File satisfies the Reader interface by implementing the Read method.type Reader interface { Read(p []byte) (n int, err error) } type File struct {} func (f File) Read(p []byte) (int, error) { // read data into p return 0, nil }
This program shows a Person type that satisfies the Greeter interface by having a Greet method. The sayHello function accepts any Greeter. We pass a Person to it, and it works because Person satisfies the interface.
package main import "fmt" type Greeter interface { Greet() string } type Person struct { name string } func (p Person) Greet() string { return "Hello, " + p.name } func sayHello(g Greeter) { fmt.Println(g.Greet()) } func main() { p := Person{name: "Alice"} sayHello(p) // Person satisfies Greeter interface }
Interface satisfaction is checked automatically by the Go compiler.
If a type misses even one method from the interface, it does not satisfy it.
You can use interfaces to write more testable and flexible code.
Interfaces define a set of methods a type must have.
A type satisfies an interface by implementing all its methods.
Go uses implicit interface satisfaction, so no extra declaration is needed.