Junior — Middle
What is the difference between interfaces in the Go language compared to interfaces in other programming languages?
sobes.tech AI
Answer from AI
In Go, interfaces are different because they are implicit — a type does not need to explicitly declare that it implements an interface. If a type contains all the methods of an interface, it is automatically considered to implement it.
This differs from many other languages where you need to explicitly declare that a class or type implements an interface.
Example:
package main
import "fmt"
type Reader interface {
Read(p []byte) (n int, err error)
}
type File struct {}
func (f File) Read(p []byte) (n int, err error) {
// implementation
return 0, nil
}
func main() {
var r Reader
var f File
r = f // File automatically implements Reader
fmt.Println(r)
}