Object-oriented programming in Golang

Object-oriented programming is a paradigm that works with classes and objects. Go doesn’t have supports for classes and objects. But in Go, we can do some Object-orientation. In a sense, Go allows for lightweight OOP.

Types in Go

Go supports custom types via structs. This allows defining custom data structure as well as class-like behavior in Go. Types can have methods associated with them. Here is an example of a custom type.

package main

import "fmt"

type Student struct {
	Name string
	Roll int
}

func (s Student) Print() {
	fmt.Println(s)
}

func main() {

	jack := Student{"Jack", 123}

	jack.Print() // {Jack 123}

}

In the code above, Student struct is a custom type. It also has a method print which it can directly call from an object of its type.

This type system in Go emulates class-like behavior.

Inheritance

In OO-languages they support inheritance. In Go inheritance is not simple. In order to do it successfully one must employ struct embedding to have the inheritance. This shows that Go supports inheritance even though Go is not a strict OO-language.

Polymorphism

Polymorphism is another property an OO-language has. It is the property where an object behaves like another object and thus shows polymorphic behavior.

Go can also achieve polymorphism via interfaces. When a type implements interfaces it behaves like that type. This is how polymorphism is done in Go.

Object-orientation in Go

As can be seen, Go shows multiple different ways it can emulate object orientation. In that sense, it is a lightweight OO-language. Even though Go doesn’t strictly support OO it can do close to that.