Middle
What is an interface in Go and how is it structured internally?
sobes.tech AI
Answer from AI
In Go, an interface is a set of methods that describe behavior. Any type that implements all the methods of the interface automatically satisfies that interface, without explicit declaration.
Inside, the interface is represented by a structure with two fields: a pointer to the type descriptor and a pointer to the data (value). This allows the interface to hold a value of any type that implements the interface's methods and to call them dynamically.
Example of an interface and its implementation:
type Reader interface {
Read(p []byte) (n int, err error)
}
type File struct {}
func (f *File) Read(p []byte) (int, error) {
// implementation of read
return 0, nil
}
var r Reader = &File{} // File implements Reader
Thus, in Go, an interface is a polymorphism mechanism based on implicit implementation and dynamic binding through internal pointers.