Implement an Abstract Class in Go!
Using Interfaces and Structs to Replicate Abstract Behavior in Go

full stack dev | SaaS | AI | maker - builder
Search for a command to run...
Using Interfaces and Structs to Replicate Abstract Behavior in Go

full stack dev | SaaS | AI | maker - builder
No comments yet. Be the first to comment.
Because sometimes your models need to gossip with each other

Whether you are a SysAdmin or Causal Linux (Ubuntu/Debian) User, here is a Guide to Rescue Your Development Environment Without Breaking a Sweat

Because Not All Code Guards Need to Break the Bank

Harnessing the Power of Pydantic for Seamless AI Integration

From Simple Chat-bots to Autonomous Digital Assistants

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.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof"
In Go, you can define an interface to represent the abstract methods and use struct embedding to simulate shared behavior.
Define the interface to represent the abstract method.
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
}
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.
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