Junior — Middle
What is the difference between the interface in Go language and what features should be known?
sobes.tech AI
Answer from AI
In Go language, an interface is a set of methods that a type must implement to be considered as conforming to that interface. Features of interfaces in Go:
- Implicit implementation: a type is considered to implement an interface if it has all the methods of the interface, without explicit declaration.
- Interfaces describe behavior, not data structures.
- Empty interface (
interface{}) — an interface with no methods, which can hold a value of any type. - Interfaces can be nested, combining methods from multiple interfaces.
Example:
package main
import "fmt"
type Reader interface {
Read(p []byte) (n int, err error)
}
type MyReader struct {}
func (r MyReader) Read(p []byte) (n int, err error) {
// read implementation
return 0, nil
}
func main() {
var r Reader = MyReader{} // MyReader implicitly implements Reader
fmt.Println(r)
}