Junior — Middle
Can a struct in Go implement an interface, and how can it be done?
sobes.tech AI
Answer from AI
Yes, in Go a struct can implement an interface. For this, the struct must have all the methods declared in the interface. In Go, implementing an interface does not require explicit declaration — if the struct has the necessary methods, it is automatically considered to implement the interface.
Example:
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 main() {
var s Speaker = Person{Name: "Ivan"}
fmt.Println(s.Speak())
}
In this example, Person implements the Speaker interface because it has a Speak() method with the required signature.