Welcome to our deep dive into Go Interfaces! In this lesson, we'll explore the power of interfaces and how they help in creating flexible, reusable, and extensible code. By the end of this lesson, you'll have a solid understanding of Go interfaces, their benefits, and practical use cases.
In simple terms, an interface is a contract that defines a set of methods. A type (struct, function, pointer, etc.) that fulfills all the methods defined in an interface is said to implement that interface.
Let's consider a real-world example: A Mobile interface could define methods like Call(), Text(), and Data(). Any device that can perform these actions (smartphones, tablets, smartwatches) would implement this interface.
type Mobile interface {
Call()
Text()
Data()
}To implement an interface, a type must define all the methods specified in the interface. Let's create a Smartphone struct and implement our Mobile interface.
type Smartphone struct {
brand string
}
func (s *Smartphone) Call() {
fmt.Println("Calling...", s.brand)
}
func (s *Smartphone) Text() {
fmt.Println("Texting...", s.brand)
}
func (s *Smartphone) Data() {
fmt.Println("Using Data...", s.brand)
}
func main() {
myPhone := &Smartphone{"Apple"}
myPhone.Call()
myPhone.Text()
myPhone.Data()
}Now, myPhone is an instance of the Smartphone struct that implements the Mobile interface.
One cool feature of Go is type embedding, which can be combined with interfaces. When an interface is embedded into a type, the type automatically implements the methods of the interface.
type Device interface {
TurnOn()
TurnOff()
}
type SmartDevice struct {
Device
brand string
}
func (d *SmartDevice) TurnOn() {
fmt.Println("Turning on", d.brand)
}
func (d *SmartDevice) TurnOff() {
fmt.Println("Turning off", d.brand)
}
func main() {
myDevice := &SmartDevice{Device{}, "Apple"}
myDevice.TurnOn()
myDevice.TurnOff()
}In this example, SmartDevice embeds the Device interface and implements both TurnOn() and TurnOff() methods, thus implementing the Device interface automatically.
What is an interface in Go?
Why are interfaces useful in Go?
Keep exploring the world of Go interfaces, and happy coding! 🚀