Sobes.tech
Junior — Middle

How does the compiler specify that a class implements a certain interface?

sobes.tech AI

Answer from AI

In Go, interface implementation is implicit: a type is considered to implement an interface if it contains all the methods declared in the interface.

That is, to indicate to the compiler that a type implements an interface, it is enough to implement all the interface's methods with the required signature.

Example:

package main

import "fmt"

type Speaker interface {
    Speak() string
}

type Dog struct {}

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

func main() {
    var s Speaker = Dog{} // Dog implements the Speaker interface
    fmt.Println(s.Speak())
}

Here, Dog implements the Speak() method, so the compiler considers that Dog implements the Speaker interface. No explicit declaration is required.

How does the compiler specify that a class implements… - sobes.tech