search

What is the difference between Go's implicit and explicit implementation of interfaces?

In Go, interfaces can be implicitly or explicitly implemented by a type.

Implicit implementation means that a type satisfies an interface if it has all the methods defined in the interface. In other words, if a type has the same method signatures as an interface, it implicitly implements that interface. Here's an example:

type Speaker interface {
    Speak()
}

type Dog struct {}

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

func main() {
    var s Speaker
    s = Dog{}
    s.Speak() // Output: Woof!
}

In this example, **Dog** implicitly implements the **Speaker** interface because it has a method with the same signature as the **Speak** method in the **Speaker** interface.

Explicit implementation means that a type explicitly declares that it implements an interface by using the interface name in its definition. Here's an example:

type Speaker interface {
    Speak()
}

type Dog struct {}

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

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

func main() {
    var s Speaker
    s = Dog{}
    s.Speak() // Output: Woof!
    // s.Bark() // This will not compile
}

In this example, **Dog** explicitly implements the **Speaker** interface by defining a **Speak** method. The **Bark** method is not part of the interface and cannot be called on a variable of type **Speaker**.

In general, it is recommended to use implicit implementation in Go, as it leads to more flexible and extensible code. Explicit implementation should only be used when necessary, such as when a type needs to implement multiple interfaces with conflicting method signatures.

Related Questions You Might Be Interested