Welcome to our comprehensive guide on Go Interfaces! In this lesson, we'll explore how to create, use, and implement interfaces in Go. This knowledge is crucial for structuring clean, flexible, and maintainable code.
Interfaces in Go are a powerful tool to define a common behavior or contract that can be shared by various types. An interface lists a set of method signatures without providing any implementation.
// Define an interface called Shape
type Shape interface {
Area() float64
Perimeter() float64
}š Note: An interface in Go consists of method signatures without any implementation.
To implement an interface, a type must define all the methods specified in the interface. Here's how we can implement the Shape interface for a Circle type:
type Circle struct {
radius float64
}
// Implement Area and Perimeter methods for Circle
func (c Circle) Area() float64 {
return 3.14 * c.radius * c.radius
}
func (c Circle) Perimeter() float64 {
return 2 * 3.14 * c.radius
}š Note: To implement an interface method, use the type name followed by a dot (type . MethodName) before the method definition.
You can declare variables of an interface type and assign them instances of types implementing the interface. To call methods on these variables, use the interface method name:
func main() {
// Create a Circle instance
circle := Circle{radius: 5}
// Define a Shape variable and assign it the Circle instance
var shape Shape = circle
// Call Area and Perimeter methods on the Shape variable
fmt.Println("Area:", shape.Area())
fmt.Println("Perimeter:", shape.Perimeter())
}What is the primary purpose of using an interface in Go?
We've covered the basics of Go interfaces! In the next lesson, we'll dive deeper into using interfaces in real-world examples and explore advanced concepts like type assertions and interface embedding.
Happy coding! šš