Sobes.tech
Senior

How is the interface in Go structured?

sobes.tech AI

Answer from AI

In Go, an interface is a set of methods that a type must implement to be considered as implementing that interface. Interfaces in Go are implicit: a type automatically implements an interface if it has all the methods of that interface.

An interface defines behavior, not data structures. This allows for writing flexible and extensible code.

Example of an interface and its implementation:

package main
import "fmt"

// Define the interface
type Speaker interface {
    Speak() string
}

// Type implementing the interface
type Dog struct {}
func (d Dog) Speak() string {
    return "Woof!"
}

// Another type
type Cat struct {}
func (c Cat) Speak() string {
    return "Meow!"
}

func main() {
    var s Speaker

    s = Dog{}
    fmt.Println(s.Speak()) // Woof!

    s = Cat{}
    fmt.Println(s.Speak()) // Meow!
}

Key features of interfaces in Go:

  • Implicit implementation — no need to explicitly declare that a type implements an interface.
  • Interfaces can be nested.
  • Interfaces allow writing code that works with different types through a common contract.
  • The empty interface interface{} can hold values of any type.

Thus, interfaces in Go are a powerful tool for abstraction and polymorphism.