Tell me about interfaces in Go: what are they, what do they consist of, what is a nil interface?
sobes.tech AI
Answer from AI
In Go, an interface is a set of methods that a type must implement to be considered as implementing that interface. An interface describes behavior, not data structure.
An interface consists of a list of method signatures, for example:
type Reader interface {
Read(p []byte) (n int, err error)
}
Any type that implements the method Read([]byte) (int, error) automatically satisfies the Reader interface.
A nil interface is an interface that contains neither a value nor a type. Its value is nil. It is important to understand that in Go, an interface is a pair: (type, value). If both type and value are nil, the interface is considered nil. If the type is present but the value is nil, the interface is not nil.
Example:
var r io.Reader // r == nil
var p *os.File = nil
r = p // r != nil, because the type is *os.File, even though the value is nil
if r == nil {
fmt.Println("r is nil")
} else {
fmt.Println("r is not nil")
}
This often causes confusion when checking for nil with interfaces.