Sobes.tech
Middle+

What are interfaces in Go?

sobes.tech AI

Answer from AI

In Go, interfaces are a set of methods that a type must implement to be considered as conforming to that interface. They allow describing behavior without specifying a concrete implementation, which promotes flexibility and polymorphism.

Features of interfaces in Go:

  • Implicit implementation: a type is considered to implement an interface if it has all the methods of the interface, without needing to explicitly declare it.
  • Interfaces can be used for abstraction and simplifying testing.

Example of an interface and implementation:

package main
import "fmt"

type Speaker interface {
    Speak() string
}

type Dog struct {}

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

type Cat struct {}

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

func saySomething(s Speaker) {
    fmt.Println(s.Speak())
}

func main() {
    dog := Dog{}
    cat := Cat{}
    saySomething(dog) // Outputs: Woof!
    saySomething(cat) // Outputs: Meow!
}

Thus, interfaces allow writing more universal and extendable code.