Luigi
Published on

Understanding Object Oriented Programming in Golang

banner

Prerequisites

  • Go local installation (v1.18)
  • A code editor
  • Basic understanding of Go

Introduction

Object oriented programming (OOP) is a paradigm which uses the idea of representing real life obejects OR entities in code. While this paradigm is in use, code is arranged based on functionality; thereby enabling abstraction, re-usability, efficiency and faster maintenance by the engineers.

In, OOP there are three basic but very important concepts that you have to understand viz Classes, Methods and Objects.

  • A class is a user defined data type that acts as a blueprint for objects, attributes and methods.
  • An object is an instance of a class.
  • A method are functions defined in a class to describe the behaviour of objects created from a class.

However, implementation of OOP in Go is different from how you'd do it in other programming languages. OOP concepts are implemented using structs, interfaces and custom types.

What's a struct?

A struct can be defined as the blue print of an object. They are user-defined collections of fields. This implies that multiple objects can be derived from a shared struct.

In other programming languages, structs are equivalents of classes.

For example;


// Creates a person struct
type  Person struct {
    name string
    age uint32
    height float32
}

Creating objects using structs

In OOP, an object is created from a class (a struct in Go). If we want to created multiple objects from a single class, we'd do it as below:

// Instantiates the Person struct to create the user1 and user2 objects
user1 := Person {
name: "John Doe",
age: 32,
height: 160
}

user2 := Person {
name: "Jabe Doe",
age: 42,
height: 120
}

The values of an instantiated struct can be accessed using the dot notation. If we wanted to access the age of the user, we'd do it as below:

fmt.Println("Value:", user1.age)

//Output Value: 32

Methods

In OOP, a struct can contain methods that are specific to it, thus they can be used only on the specific struct type. Methods are assigned to a struct by specifying the receiver name and the struct type name before the function name. For example, to add a method to the Person struct type above,


func (person Person) printAge () {
//Code
}

// person is the receiver name
// Person is the struct
// printAge is the function name

Interfaces

An interface is a set of methods that we use to define a set of actions.

For example,

type Person interface{

Walk( direction string )
Sleep()
}

Let me know what your thoughts are about this article hi[at]luigimorel.com. Cheers!

© 2022 - 2024 Luigi Morel. All rights reserved.