Senior
What are interfaces and how do they differ from classes?
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. Unlike classes, interfaces do not contain implementations, only describing behavior.
Key differences:
- Interfaces describe only methods, while classes (in Go — structs) contain data and methods.
- In Go, there are no classes as such, only structs and interfaces.
- A type automatically implements an interface if it has all the methods of the interface (implicit implementation).
Example:
// Interface
type Reader interface {
Read(p []byte) (n int, err error)
}
// Struct implementing the interface
type File struct {}
func (f File) Read(p []byte) (n int, err error) {
// implementation
return 0, nil
}
func main() {
var r Reader = File{} // File implements Reader
}