Senior
What are the rules for working with interfaces in Go?
sobes.tech AI
Answer from AI
In Go, interfaces play a key role, and when working with them, it is important to consider a few rules:
- Interfaces should be small and specialized. It is better to create an interface with one or two methods to increase flexibility.
- Use interfaces to define behavior, not to describe data.
- Do not declare interface methods with redundant parameters — the interface should be simple and understandable.
- In Go, interface implementation is implicit: a type satisfies an interface if it implements its methods. This allows for easy substitution of implementations.
- For testing, it is convenient to create interfaces to replace real implementations with mocks.
Example of an interface with one method:
package main
import "fmt"
type Reader interface {
Read(p []byte) (n int, err error)
}
func main() {
var r Reader
// r can be any type that implements Read
fmt.Println(r)
}
This approach facilitates code extension and maintenance.