gointerface

Struct inside the interface


package main

import "fmt"

type Dog struct {
    Name string
}

type Animal interface {
    Dog
    Speak()
}

func (d Dog) Speak() {
    fmt.Println("Woof!")
}

func main() {
    d := Dog{Name: "Fido"}
    fmt.Println(d)
    d.Speak()
}

Why does the struct inside the interface not cause a compilation error?

What I have understood from the interfaces definition in Go is that interfaces are named collections of method signatures. Dog is not the method signature, if I am not mistaken.


Solution

  • It’s a valid interface, although it can only be used as a type constraint. The way that it is declared, it constrains the generic type to Dog with a method Speak. You can, for instance, do:

    func f[T Animal](a T) {
        a.Speak()
    }
    

    and instantiate f with a Dog. You cannot instantiate it with any other type.