What are interfaces in Go? What is duck typing?
sobes.tech AI
Answer from AI
In Go, interfaces define a set of methods that a type must implement to be considered as conforming to that interface. Importantly, implementing an interface in Go does not require explicit declaration — if a type implements all the methods of an interface, it is automatically considered to implement it.
Duck typing is a concept where the type of an object is determined not by its explicit declaration but by the presence of certain methods or properties. In the context of Go, this means that if an object "quacks like a duck and walks like a duck," then it is a duck, i.e., if a type implements the methods of an interface, it fits that interface.
Example of an interface and implementation in Go:
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) // Woof!
saySomething(c) // Meow!
}
Here, Dog and Cat implement the Speaker interface without explicitly declaring it, thanks to the presence of the Speak() method. This is an example of duck typing in Go.