Junior
What are interfaces in the Go language?
sobes.tech AI
Answer from AI
In Go, an interface is a collection of method signatures. It defines the behavior of an object: what it "can do". An interface does not contain data or method implementations.
Key features:
- Implicit implementation: A type implements an interface implicitly if it provides all the methods declared in the interface. There is no need to explicitly declare that a type implements an interface.
- "Duck typing": "If it quacks like a duck and walks like a duck, then it is a duck." In Go, the type of the object is less important than whether it implements the required set of methods.
- Zero value: The zero value of an interface is
nil. An interface value can benilif both its type and value inside it arenil. - Empty interface (
interface{}orany): Can hold a value of any type. Often used for working with data of unknown type or in generic containers.
Example of defining and using an interface:
// Define the Greeter interface
type Greeter interface {
Greet() string // Method Greet that returns a string
}
// Define the Person type
type Person struct {
Name string
}
// Person implements the Greeter interface by providing the Greet method
func (p Person) Greet() string {
return "Hello, " + p.Name
}
// Define the Robot type
type Robot struct {
Model string
}
// Robot also implements the Greeter interface
func (r Robot) Greet() string {
return "Hi, model " + r.Model
}
// Function that takes a Greeter interface
func SayHello(g Greeter) {
fmt.Println(g.Greet()) // Call the Greet method via the interface
}
func main() {
person := Person{Name: "Alice"}
robot := Robot{Model: "RX-800"}
SayHello(person) // Pass a Person that implements Greeter
SayHello(robot) // Pass a Robot that implements Greeter
}
Interfaces promote flexibility and decoupled design, allowing you to write functions that work with different data types as long as those types implement the required interface. They are used for creating generic code and in the standard library of Go (e.g., io.Reader, io.Writer, fmt.Stringer).