How do interfaces work in Go? Explain duck typing and implicit satisfaction
go-jun-003
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
In Go, interface satisfaction is implicit — a type implements an interface simply by having all the required methods with matching signatures. There is no explicit 'implements' keyword. This is structural typing (duck typing): if it has the method, it satisfies the interface. A key consequence: a type can implement an interface defined in a different package without importing that package. This decouples packages and enables writing against interfaces you didn't design. The empty interface (interface{} or any in Go 1.18+) is satisfied by every type. Interface values contain two words: a pointer to the type descriptor and a pointer to the data. The nil interface (both nil) differs from an interface holding a nil pointer — a common source of bugs.
Code example
package main
import "fmt"
// Interface defined in this package
type Stringer interface {
String() string
}
// Concrete type — no explicit declaration needed
type Point struct{ X, Y int }
func (p Point) String() string {
return fmt.Sprintf("(%d, %d)", p.X, p.Y)
}
// Works anywhere Stringer is expected
func Print(s Stringer) { fmt.Println(s.String()) }
func main() {
p := Point{3, 4}
Print(p) // (3, 4) — satisfies Stringer implicitly
// Nil interface trap
var s Stringer // nil interface (type=nil, value=nil)
var p2 *Point // typed nil pointer
s = p2 // s is now non-nil interface wrapping nil *Point!
fmt.Println(s == nil) // false — trap!
}
Follow-up
What is the nil interface trap: a non-nil interface wrapping a nil concrete pointer? Show the problematic pattern.