Hey there, fellow Go newbies (or should I say Gophers-in-trainingš§)! š±
Interfaces seemed like one of those mysterious, magical things that everyone kept talking about but no one really explained in a way that made sense. āItās like polymorphism but simpler,ā they said. āItās just like a contract,ā they claimed. But every time I tried to implement one, my code would look at me like, "What are you even doing, human?" š
But that was then. Now, interfaces and I are on much better terms, and I'm here to help you avoid my early confusion. So, if youāve been scratching your head about Go interfaces, grab a cup of coffee (or tea), and letās break it down, one step at a timeāminus the headaches. š”
So, What Exactly Is an Interface?
Letās start from the very top. In Go, an interface is basically a way to define behavior, but without getting bogged down by the details of how it works. Imagine youāre the boss of a factory, and you donāt care how the machine works; you just care that it can produce the product. Thatās what Go interfaces are like: you define what needs to happen, but not how it should be done.
For example, letās pretend weāre working with animals (yes, Go works with animals, stay with me here). You know every animal makes a sound, but you donāt really care how that happens. Dogs bark, cats meow, and ducksā¦well, they quack. You can define an interface like this:
type Animal interface {
Sound() string
}
Whatās this? Just a contract, saying: "Hey, any type that wants to be called an Animal must have a Sound() method." Thatās it! No weird wizardry involved.
Show Me the Code! š¶š±š¦
Letās take a super simple example and see how it works in action. Weāll create some animals and make them speak.
package main
import "fmt"
// The Animal interface
type Animal interface {
Sound() string
}
// Define a Dog
type Dog struct{}
func (d Dog) Sound() string {
return "Woof!"
}
// Define a Cat
type Cat struct{}
func (c Cat) Sound() string {
return "Meow!"
}
func main() {
// Our Animal variable can hold any type that satisfies the interface
var myPet Animal
// myPet is now a Dog
myPet = Dog{}
fmt.Println(myPet.Sound()) // Outputs: Woof!
// myPet is now a Cat
myPet = Cat{}
fmt.Println(myPet.Sound()) // Outputs: Meow!
}
Whatās happening here?
- We define an Animal interface that has one method: Sound() š.
- Then we create two types, Dog and Cat, and give them their unique Sound() methods.
- In the main() function, we create a variable myPet that can hold anything that satisfies the Animal interface.
- First, we assign a Dog, and boom! Our dog barks: "Woof!" š
- Then we assign a Cat, and guess what? It meows: "Meow!" š
Hereās where the magic of Go interfaces really kicks in š„š„:
as long as a type has the required method, it satisfies the interface. No need to explicitly say "Dog implements Animal"āGo is smart enough to figure it out on its own! š§ š”
Why Should You Care About Interfaces?
Let me level with you. At first, I was like, āWhy even bother with this? I can just write my methods directly!ā But trust me, youāll want to understand interfaces sooner rather than later, especially when your codebase starts to grow.
Hereās why:
- Flexibility: Interfaces make your code more flexible. You can swap out one type for another as long as it satisfies the interface. Itās like hiring someone based on their skills rather than their job title.
Polymorphism: You can treat different types uniformly if they implement the same interface. This is what makes interfaces so powerfulāitās like having a universal remote that works with any TV.
Clean Code: Interfaces allow you to write cleaner, more modular code. You define behaviors and let the types handle their own implementation.
Multiple Methods, No Problem!
Letās kick it up a notch. Say youāre building a system to work with shapes, and you want to calculate both area and perimeter for different shapes like circles and rectangles. Enter the multi-method interface!
package main
import "fmt"
// Shape interface with two methods
type Shape interface {
Area() float64
Perimeter() float64
}
// Rectangle struct
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
// Circle struct
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * 3.14 * c.Radius
}
func main() {
var shape Shape
shape = Rectangle{Width: 5, Height: 4}
fmt.Println("Rectangle Area:", shape.Area()) // Outputs: 20
fmt.Println("Rectangle Perimeter:", shape.Perimeter()) // Outputs: 18
shape = Circle{Radius: 3}
fmt.Println("Circle Area:", shape.Area()) // Outputs: 28.26
fmt.Println("Circle Perimeter:", shape.Perimeter()) // Outputs: 18.84
}
The Empty Interface (interface{})
Oh, you thought we were done?ššš Nope! Letās go a bit deeper with the empty interface, interface{}, which is Goās way of saying, āI can hold any type.ā Itās like a free-for-all box where you can throw in anythingāstrings, numbers, structsāyou name it.
package main
import "fmt"
func PrintAnything(val interface{}) {
fmt.Println(val)
}
func main() {
PrintAnything("Hello, Gophers!") // Outputs: Hello, Gophers!
PrintAnything(42) // Outputs: 42
PrintAnything(true) // Outputs: true
}
The empty interface is often used in situations where you donāt know ahead of time what type youāll be dealing with (think APIs or libraries). Itās like Goās version of a wildcard.
Embrace the Interface
Learning Go interfaces can feel like navigating a labyrinth at first, but once you grasp the basics, it opens up a whole new world of flexible, reusable, and clean code. So donāt be afraid to dive in!
Start simple, play with small examples, and let Goās interface magic grow on you. Before long, youāll be writing code thatās as clean and flexible as a yoga instructor at a tech conference.
Happy coding, fellow Gophers! May your interfaces be simple, and your structs be ever-implementing. šāļø
Top comments (19)
Go makes me love my job :)
Hey martin..indeed Go is the best language so far to work with especially while focusing on the back-end side..Looking foward to collaborate with you in any kind of projects you need assistance
reach me out thru my email : allangithaiga5@gmail.com
Best regards,
Allan Githaiga
This is true for services development in general, not just web backends, and those issues I used to find vexing (vendor caching, for offline builds, for example) are now long gone. It remains clean to read with long term stability in the compiler and ecosystem, so you don't have things constantly change and break every time you happen to do a newer build...
This article is one of the most useful I've read recently about GoLang, especially regarding interfaces. Thank you!
this article was one of the worst
All articles at this level, don't answer the question
āWhy not use the original structure ?ā
If you don't use an interface, you'd end up duplicating a lot of the same methods (like Area() and Perimeter()) across different structs. The benefit of the interface comes when you need to handle a diverse range of shapes without constantly worrying about the details of each one.
I too worry too much when working in Go. Thank you for this guide!
If I may ask how do you make your blog banners especially the Go character?
well i just modify them using UX tools like figma,miro or canva
great article @githaiga22 , this is a nice and fun way to explain interfaces.
Nice article, straight to the point.
Salut Ć tous.
Je suis dƩveloppeur d'application Android et je viens juste de terminer mon application gratuite de philosophie.
J'aimerais avoir des testeurs pour m'aider Ć l'amĆ©liorer. Voici mon adresse mail :
Laminefalldeveloppeur@gmail.com
nice learning interface and struct diffrances
Just a heads up that you can add highlighting to the code blocks if you'd like. Just change:
... to specify the language:
More details in our editor guide!
Some comments have been hidden by the post's author - find out more