DEV Community

Aleson França
Aleson França

Posted on

Go Interfaces Simplified: A Beginner's Tutorial 🚀

if you're starting with golang, you probably heard about interfaces, but you may not fully understand how they work.
Interfaces are one of the most powerful concept in the lang, allowing you to write flexible and reusable code.

What Are Interfaces ?

In go, an interface is a set of methods that a type can implement. Unlike other, we don't need to explicity declare that a type implements an interface it simply does so if it has the required methods

Simples Interface Example

package main

import "fmt"

// Interface definition
type Animal interface {
    Speak() string
}

// Structs implementing the interface
type Dog struct{}

func (d Dog) Speak() string {
    return "Woof!"
}

type Cat struct{}

func (c Cat) Speak() string {
    return "Meow!"
}

func main() {
    var a Animal

    a = Dog{}
    fmt.Println("Dog says:", a.Speak())

    a = Cat{}
    fmt.Println("Cat says:", a.Speak())
}
Enter fullscreen mode Exit fullscreen mode

What's happening here ?

We define the Animal interface with Speak() method.

Dog and Cat automatically implement this interface since they have the Speak() method.

In main(), we assign diff structs to an Animal variable, demonstrating polymorphism in Go

Empty Interfaces: interface{}

In go, the empty interface is special type that can hold any value:

func printValue(v interface{}) {
    fmt.Println("Received value:", v)
}

func main() {
    printValue(42)
    printValue("Hello, Go!")
    printValue(3.14)
}
Enter fullscreen mode Exit fullscreen mode

📍This is useful but should be use with caution to avoid type loss and the need for type asserts.

Interfaces with Mutiple methods

we can define more complex interfaces that require multiple methods. Example:

package main

import "fmt"

// Interface with two methods
type Vehicle interface {
    Start() string
    Stop() string
}

// Implementation for a Car
type Car struct{}

func (c Car) Start() string {
    return "Car started!"
}

func (c Car) Stop() string {
    return "Car stopped!"
}

func main() {
    var v Vehicle = Car{}
    fmt.Println(v.Start())
    fmt.Println(v.Stop())
}
Enter fullscreen mode Exit fullscreen mode

Here, Car implements Vehicle because it has the Start() and Stop() methods.

💡 Conclusion

  • Interfaces in go are powerful and enable flexible code.
  • The empty interface (interface{}) can be useful but requires caution.
  • Unlike other Langs, go uses implicit implementation

Top comments (0)