Implement an Abstract Class in Go!

Nikhil AkkiNikhil Akki
2 min read

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

0
Subscribe to my newsletter

Read articles from Nikhil Akki directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nikhil Akki
Nikhil Akki

I am a Full Stack Solution Architect at Deloitte LLP. I help build production grade web applications on major public clouds - AWS, GCP and Azure.