How to Implement Interface in Go: Simple Guide with Examples
interface by defining methods with the same names and signatures as the interface requires on your struct or type. There is no explicit declaration; if your type has all the methods, it automatically implements the interface.Syntax
An interface in Go is a set of method signatures. To implement it, a type must have all those methods with matching signatures. There is no need to explicitly say you implement an interface; Go checks this automatically.
- interface: defines method names and signatures.
- type (usually struct): implements those methods.
- no explicit keyword: implementation is implicit.
type Speaker interface { Speak() string } type Person struct { Name string } func (p Person) Speak() string { return "Hello, my name is " + p.Name }
Example
This example shows a Speaker interface and a Person struct that implements it by defining the Speak method. The SaySomething function accepts any Speaker and calls its Speak method.
package main import "fmt" type Speaker interface { Speak() string } type Person struct { Name string } func (p Person) Speak() string { return "Hello, my name is " + p.Name } func SaySomething(s Speaker) { fmt.Println(s.Speak()) } func main() { p := Person{Name: "Alice"} SaySomething(p) }
Common Pitfalls
1. Forgetting to implement all methods: If your type misses any method from the interface, it won't implement it.
2. Pointer vs value receiver mismatch: If the interface method uses a pointer receiver but your type method uses a value receiver (or vice versa), the implementation may fail.
3. No explicit declaration: Some expect to write implements keyword, but Go does not use it.
package main import "fmt" type Reader interface { Read() string } type File struct { Content string } // Wrong: method name typo, so File does NOT implement Reader func (f File) Reed() string { return f.Content } func main() { var r Reader f := File{Content: "data"} // This will cause compile error: cannot use f (type File) as type Reader // r = f fmt.Println("Fix method name to Read to implement Reader") }
Quick Reference
- Define an interface with method signatures.
- Implement all methods on your type with matching signatures.
- Use pointer receivers if methods modify the receiver or to match interface expectations.
- No explicit declaration needed; implementation is automatic.
- Interfaces can hold any type that implements their methods.