Imagine you have different animals: a dog, a cat, and a robot dog.
They’re all different… but if they can speak, then you can treat them the same:
“If you can
Speak(), then you’re good to go!”
That’s what interfaces are — rules that types can follow.
An interface is a set of method signatures.
Here’s an example:
type Speaker interface {
Speak()
}This means:
“Any type that has a
Speak()method is aSpeaker.”
type Dog struct {
Name string
}
func (d Dog) Speak() {
fmt.Println(d.Name, "says: Woof!")
}
type Robot struct {
ID string
}
func (r Robot) Speak() {
fmt.Println("Robot", r.ID, "says: Beep boop.")
}Both Dog and Robot now have a Speak() method, so they satisfy the Speaker interface — automatically! 🧠
func makeItSpeak(s Speaker) {
s.Speak()
}Now you can pass in anything that speaks:
d := Dog{Name: "Buddy"}
r := Robot{ID: "XJ9"}
makeItSpeak(d)
makeItSpeak(r)Output:
Buddy says: Woof!
Robot XJ9 says: Beep boop.You can write generic functions that work on many types
You don’t need to manually declare that something implements an interface
It’s automatic — if your type has the right methods, it just works
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func printArea(s Shape) {
fmt.Println("Area is:", s.Area())
}Now call:
c := Circle{Radius: 5}
r := Rectangle{Width: 4, Height: 3}
printArea(c)
printArea(r)Interfaces are like contracts: “If you have these methods, you’re in.”
They help you write flexible, reusable code
Structs don’t need to declare they follow an interface — Go figures it out for you
Great for making code polymorphic (same function, different types)
No posts

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.