Exercise 2: Interfaces and Polymorphism in Go

Learn how to use interfaces in Go to apply polymorphism.

What is an Interface in Go?

An interface in Go defines a behavior that a type must implement. Unlike other languages, Go does not use an `implements` keyword.

type Animal interface {
    Speak() string
}

Why Use Interfaces?

  • Flexibility: Allows defining behavior without worrying about specific types.
  • Polymorphism: A function can accept multiple different types as long as they implement the same interface.
  • Modularity: Makes code more reusable and adaptable.

Comparison with Other Languages

  • Java: Uses `implements` to explicitly declare that a class implements an interface.
  • Python: Uses abstract classes and duck typing.
  • C++: Interfaces are often handled via abstract classes.

Exercise Instructions

  • Create a file interfaces.go
  • Define an interface `Animal` with a method `Speak()`.
  • Create two structures `Dog` and `Cat` that implement this interface.
  • Implement the `Speak()` method for each type.
  • Test using a function that prints each animal's sound.
package main

import "fmt"

type Animal interface {
    Speak() string
}

type Dog struct {}
type Cat struct {}

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

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

func MakeSound(a Animal) {
    fmt.Println(a.Speak())
}

func main() {
    dog := Dog{}
    cat := Cat{}
    
    MakeSound(dog)
    MakeSound(cat)
}

Expected Output

Woof!
Meow!

Learn More

For more details on Go interfaces, check out:

Official Go Documentation
← Previous Exercise Next Exercise →

🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee