Junior — Middle
Can you explain what interfaces are in the Go language and how they work?
sobes.tech AI
Answer from AI
In Go, an interface is a set of methods that a type must implement to be considered as conforming to that interface. Interfaces allow describing behavior without specifying a concrete implementation, which promotes polymorphism.
Features of interfaces in Go:
- Implicit implementation: a type is considered to implement an interface if it has all the methods of the interface, without explicit declaration.
- An interface can contain one or more methods.
- A variable of interface type can hold a value of any type that implements this interface.
Example:
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) // Outputs: Woof
saySomething(c) // Outputs: Meow
}
Thus, interfaces enable writing flexible and extensible code by operating on abstractions rather than concrete types.