Interfaces & Implicit Duck Typing

๐Ÿน Go Language Lesson 12 Advanced

Interfaces define behavior contracts. C# and Java enforce explicit interface declarations, while Go implements interfaces implicitly.

1 Duck Typing (Implicit Implementation)

Go interfaces are implemented **implicitly**. If a struct implements all the methods defined by an interface, Go automatically considers that the struct implements the interfaceโ€”**no `implements` or `extends` keywords are required.** This is known as structural typing or "Duck Typing" ("if it walks like a duck and quacks like a duck, it is a duck").

2 Interfaces Code

Let's run a program illustrating implicit interfaces and runtime dispatch polymorphism:

Go โ€” Interfaces & Polymorphism โ–ถ Run Code
package main

import "fmt"

interface Speaker {
    Speak() string
}

struct Dog struct{}

// Dog implicitly implements Speaker because it defines Speak()
func (d Dog) Speak() string {
    return "Woof!"
}

struct Cat struct{}

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

func main() {
    // Array of Speaker interfaces
    speakers := []Speaker{Dog{}, Cat{}}

    for _, s := range speakers {
        fmt.Println(s.Speak()) // Runtime dynamic dispatch
    }
}
3 Code Challenge
Challenge: Create an interface called `Shape` with a method `Area() float64`. Create a struct called `Square` that implicitly implements the interface. Instantiate `Square` and assign it to a `Shape` reference to test polymorphic assignment.