Skip to main content

Command Palette

Search for a command to run...

Implement an Abstract Class in Go!

Using Interfaces and Structs to Replicate Abstract Behavior in Go

Updated
2 min read
Implement an Abstract Class in Go!

Well in Go, there is no direct equivalent of Python's abstract classes, but you can achieve similar functionality using interfaces and struct embedding. Here's how you can replicate the behavior of an abstract class in Go.

Python Abstract Class Example:

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        return "Woof"

Go Equivalent Using Interfaces and Struct Embedding:

In Go, you can define an interface to represent the abstract methods and use struct embedding to simulate shared behavior.

  1. Define the interface to represent the abstract method.

  2. Use structs to implement that interface.

Here’s an equivalent example in Go:

package main

import "fmt"

// Define an interface similar to an abstract method
type Animal interface {
    MakeSound() string
}

// Define a struct representing the base class (optional if you need shared fields)
type BaseAnimal struct {
    // you can add fields common to all animals here
}

// Define another struct implementing the abstract method
type Dog struct {
    BaseAnimal // Embedding BaseAnimal struct to inherit shared fields (if any)
}

// Implement the interface method for Dog
func (d Dog) MakeSound() string {
    return "Woof"
}

func main() {
    var animal Animal = Dog{}
    fmt.Println(animal.MakeSound()) // Output: Woof
}

Key Concepts:

  • Animal interface is equivalent to the abstract class method in Python.

  • BaseAnimal struct is used if you need shared fields or behavior, similar to a base class in Python (though it's not necessary if you're only using abstract methods).

  • Struct Dog implements the Animal interface by providing the MakeSound() method, similar to a subclass overriding an abstract method in Python.

Summary

In Go, interfaces define abstract methods, and structs implement those methods. You can combine them with struct embedding to share common functionality across different types.

References

https://gobyexample.com/interfaces

https://www.alexedwards.net/blog/interfaces-explained

Image Attribution

Image #1

Image #2

Go & Gopher

Go

Part 3 of 16

In this series, we will learn Go from the very basics to advance topics.

Up next

Channels in Go

Understanding Channel model for concurrency in Golang