Definition

An interface defines the behavior of a type. By behavior, we mean that it defines a "list" of methods that a type must have in order for that type to be considered to implement its interface.

For example, look at the following type:


type Person struct {
    string name
🇧🇷

func(p Person) speak(string phrase) {
    fmt.Printf("%s says: %s", p.Name, sentence)
}
                        

Note that it has the Speak() method. Now imagine that we have several different types that have the same method, and we want to call it inside a function that will receive any type that has that method.

For this, we use an interface that asks for this method:


type Talker interface {
    speak(string)
}
                        

With this interface, we can now create a function that accepts any type that implements it, leaving aside the need to write a function for each type that has the Speak() method.

definicao.go