~/Object Oriented Programming in Golang

Apr 15, 2023


Golang does not have traditional object oriented programming features like classes and inheritance. Instead, it uses structs and interfaces to achieve similar results.

Structs are used to define composite types:

1
2
3
4
5
6
7
type Animal struct {
    Name string
}

func (a Animal) Speak() string {
    return a.Name + " makes a sound"
}

Interfaces specify what methods a type must have:

1
2
3
type Speaker interface {
    Speak() string
}

You can then use these to implement a form of polymorphism:

1
2
3
func MakeSpeak(s Speaker) {
    fmt.Println(s.Speak())
}

There is no inheritance. Instead, Golang uses composition via embedding:

1
2
3
4
5
6
7
type Dog struct {
    Animal
}

func (d Dog) Speak() string {
    return d.Name + " barks"
}

To summarize, use structs, interfaces, and embedding for OOP in Go.

Tags: [golang] [oop]