Interfaces in Go specify method sets that types can implement. This allows different types to be treated the same way if they implement the same interface, enabling flexible and reusable code.
package main import "fmt" type Speaker interface { Speak() string } type Dog struct {} func (d Dog) Speak() string { return "Woof!" } type Cat struct {} func (c Cat) Speak() string { return "Meow!" } func saySomething(s Speaker) { fmt.Println(s.Speak()) } func main() { d := Dog{} c := Cat{} saySomething(d) saySomething(c) }
The Dog and Cat types both implement the Speaker interface by defining Speak(). The saySomething function calls Speak() on each, printing their unique sounds.
package main import "fmt" type Reader interface { Read() string } type File struct {} func (f File) Read() string { return "file content" } func main() { var r Reader r = File{} fmt.Println(r.Read()) r = nil fmt.Println(r.Read()) }
Assigning nil to the interface variable r means it holds no concrete value. Calling a method on a nil interface causes a runtime panic due to nil pointer dereference.
Option D uses the correct Go syntax for defining an interface. Options A, B, and D have syntax errors or misuse struct instead of interface.
package main import "fmt" type Processor interface { Process() string } type Image struct {} func (i Image) Process() string { return "Processing image" } type Text struct {} func (t Text) Process() string { return "Processing text" } func process(p Processor) { fmt.Println(p.Process()) } func main() { img := Image{} txt := Text{} // Which call is correct here? }
Both Image and Text implement Process with value receivers, so passing values (not pointers) works. Passing pointers would also work but is not required here.