Sobes.tech
Junior

What is duck typing?

sobes.tech AI

Answer from AI

Duck typing is a style of dynamic typing where the type of an object or variable is determined not by its explicit inheritance or interface implementation, but by the presence of a certain set of methods or properties. If an object "walks like a duck and quacks like a duck," it is considered to be a duck.

In Go, duck typing is implemented through implicit interfaces. A struct or any other data type does not need to explicitly declare that it implements a specific interface. It is enough that the data type implements all the methods defined in the interface.

Example:

package main

import "fmt"

// Define the Speaker interface
type Speaker interface {
	Speak()
}

// Define the Dog struct
type Dog struct{}

// Dog implements the Speak() method
func (d Dog) Speak() {
	fmt.Println("Woof!")
}

// Define the Cat struct
type Cat struct{}

// Cat implements the Speak() method
func (c Cat) Speak() {
	fmt.Println("Meow!")
}

// Function takes a parameter of type Speaker
func MakeItSpeak(s Speaker) {
	s.Speak()
}

func main() {
	d := Dog{}
	c := Cat{}

	// Both Dog and Cat objects can be passed to MakeItSpeak,
	// because they both implicitly implement Speaker.
	MakeItSpeak(d)
	MakeItSpeak(c)
}

In this example, neither Dog nor Cat explicitly declare that they implement Speaker. However, since they both have a Speak() method that matches the signature in the Speaker interface, they can be used where a Speaker type is expected.

Advantages of duck typing in Go:

  • Flexibility: Allows easy creation of modular and extensible systems.
  • No rigid hierarchy: No need to inherit or explicitly implement interfaces when designing.
  • Ease of use of existing types: Any type with the necessary methods can satisfy the interface, even if it was developed without considering this interface.