Senior
type someInterface interface { someFunc() } type A struct { } func(a A) someFunc() { } type B struct { A } type C struct { some A }
sobes.tech AI
Answer from AI
The provided Go code demonstrates interfaces and structures with embedding.
- The
someInterfaceinterface defines the methodsomeFunc(). - The
Astruct implements thesomeFunc()method, soAsatisfies thesomeInterfaceinterface. - The
Bstruct embedsAanonymously, meaning it inherits all methods ofAand also satisfiessomeInterfacethrough embedding. - The
Cstruct contains a fieldsomeof typeAwith a named field, so the methods ofAare not automatically promoted toC. Therefore,Cdoes not implementsomeInterfaceunless it explicitly implementssomeFunc().
Example:
package main
import "fmt"
type someInterface interface {
someFunc()
}
type A struct {}
func (a A) someFunc() {
fmt.Println("A's someFunc")
}
type B struct {
A // anonymous embedding
}
type C struct {
some A // named field
}
func main() {
var i someInterface
a := A{}
b := B{}
c := C{}
i = a // OK
i.someFunc()
i = b // OK, through embedding
i.someFunc()
// i = c // Compilation error: C does not implement someInterface
// To make C implement the interface, explicitly define:
// func (c C) someFunc() { c.some.someFunc() }
}
Thus, anonymous embedding allows a struct to automatically implement interfaces if the embedded type does, whereas named fields do not.