Junior — Middle
What is the role of an interface in software architecture and what is it used for?
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. Interfaces allow describing behavior without tying it to a specific implementation.
Role of interfaces in architecture:
- Provide abstraction and loose coupling between components.
- Enable writing flexible and extensible code.
- Simplify testing, as interface implementations can be substituted.
Example of an interface and its implementation:
// Define the interface
type Speaker interface {
Speak() string
}
// Implementation of the interface
type Dog struct {}
func (d Dog) Speak() string {
return "Woof"
}
func MakeSpeak(s Speaker) {
fmt.Println(s.Speak())
}
func main() {
d := Dog{}
MakeSpeak(d) // Will output: Woof
}
Thus, interfaces in Go allow working with different types through a common set of methods, which improves modularity and extensibility of the code.