Junior — Middle
In which cases is it preferable to implement interfaces and where should they be declared?
sobes.tech AI
Answer from AI
In Go, interfaces are better implemented when you need to define behavior that different types can have without being tightly coupled to a specific implementation.
When to implement interfaces:
- If a function or method should work with different types, combining them with common behavior.
- To simplify testing — you can replace real implementations with mocks.
- When designing modular, extensible code.
Where to declare interfaces:
- Usually, interfaces are declared where they are used (for example, in the package where a function accepts an interface), not where they are implemented.
- This makes it easier to extend and reduces dependencies between packages.
Example:
// In the storage package
type Reader interface {
Read(p []byte) (n int, err error)
}
// In another package, you can implement this interface
func (f *File) Read(p []byte) (int, error) {
// implementation
}
This approach allows writing flexible and testable code.