Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Class and Object in Golang

  • Last Updated : 06 Sep, 2021

Every human (excluding infants) can relate to encapsulation irrespective of his/her prior knowledge of encapsulation. Do you wonder why? Simple. Recollect all the times when you were sick, and the doctor prescribed all those monstrous capsules dosage for a couple of days until you were okay again! The evil capsule contains all mysterious elements which somehow magically fit into that tiny capsule!! Ever wondered about the content inside the capsule? We only see the capsule’s external structure and honestly, none of us can tell what exactly it holds just by looking at its structure. Right? Well, to your surprise, this is what we call Encapsulation.

Wondering why we pulled Encapsulation into an article on classes and objects? Well, a class is a superb implementation of encapsulation. A capsule binds together the elements of medicine for the diseased and class binds together multiple lines of statements and/or functions for the programmer and user! Do you know what’s the funniest part? There’s no class in Golang but there is, indeed! Confusing? Seems so at first. Basically Go doesn’t have the keyword, “class ” unlike other object-oriented languages like C++/Java/Python, etc… but (here comes the exception!!!) Go supports the entire functionality of classes. It’s like Go supports classes without naming it as a class.

So what if you can’t use the keyword class? Go snatched away one keyword but gave back 4 different types of implementation of a class. Interesting! Let’s dive deeper into the details of these 4 magicians:

1. Structs (Or rather Structures )
Structs are user-defined data types/structures. They work the same as structs in other languages like C++/Python. The only difference in a normal struct and an implicit class is that struct is defined by the programmer and then passed on to a function or a method and then processed. One can never tell if the program contains a part that is implicitly going to be considered as a class but Go supports OOPs ( Object Oriented Programming System) and with that, although a name and an organized capsule isn’t visible to the programmer’s eye, we firmly believe that we can perform all OOPs functionalities in GO just in a different manner.

2. Embedding
A less popular, yet useful technique which is using embedding. As the name suggests, it supports the nesting of structures in a particular way. For instance, you have struct1 with a & b content. Now you wish to create a struct2 that includes contents of struct1 as well as c & d. In that case, you can simply mention struct1 in struct2 and then c & d, this is something like the inline function logic! Embedding is also powered by structs. There’s no difference in the implicit conversion as a class but just the case that structs are simple and nested ones are known as embedded structs.

3. Methods/Functions
Well, one can simply create functions of customized types and these functions can implicitly be treated as a class. The exciting new thing you can learn in Go’s functions is that functions have a specific receiver type and they operate only on that very particular type; unlike templates in C++.

4. Interfaces
Interfaces are like those railway platforms which contain multiple trains standing and some traveling to and fro a place. Yup, you read it right! Interfaces bind together various sets of methods that cannot be implemented explicitly as in Java. An important point to note about interfaces in Go is that names of interfaces must end with ” er ” and this is Go’s convention. The characters lying before er is actually the name of the type which implements the same name+er interface. You’ll gain maximum clarity after going through the code section below.

For instance:

Line1: type X struct {}
Line1 is a simple demo of defining X class (indirectly)

Objects can be related to real-life entities. Just as there are provisions for the functionality of a class but no class keyword, the same is the case with objects in Go. Objects or rather a variable can be instantiated with the particular class type and the variable can be further used exactly as one would use an object in any other language.

For instance:

Line2: obj := X()

Line2 is a simple demo of instantiating X class to obj (indirectly)

Code: Demonstration of Classes and Objects. 


package main
// Importing fmt package for the sake of printing
import (
// Animal is the name we want but since we are
// to use it as an interface, we will change
// the name into Animaler.
type Animaler interface {
    // Note that we will
    // declare the methods to be used
    // later here in this
    // interface
// A struct holding a string variable: SuperAnimals
type SuperAnimals struct {
    locomotion string
// An embedded struct holding content
// from another struct and two
// other string variables
// named Animals
type Animals struct {
    food  string
    sound string
// Now we are indirectly implementing
// the Animaler interface without any
// keywords.
// We are about to define each method
// declared in the Animaler interface.
func (x Animals) Eat() {
    // this method will access the variable
    // food in Animal class
func (x Animals) Move() {
    // this method will access the variable
    // locomotion in Animal class
func (x Animals) Speak() {
    // this method will access the variable
    // sound in Animal class
func (x Animals) Error() {
    fmt.Println("Invalid query entered!")
// Finally reached main function where we can
// now test our "GO classes"
func main() {
    // Experiencing a dictionary / map in GO
    // For the animal name as a key,
    // that particular object is a value
    m := map[string]Animals{
        "cow":   Animals{SuperAnimals{"walk"}, "grass", "moo"},
        "Cow":   Animals{SuperAnimals{"walk"}, "grass", "moo"},
        "Bird":  Animals{SuperAnimals{"fly"}, "worms", "peep"},
        "bird":  Animals{SuperAnimals{"fly"}, "worms", "peep"},
        "Snake": Animals{SuperAnimals{"slither"}, "mice", "hsss"},
        "snake": Animals{SuperAnimals{"slither"}, "mice", "hsss"},
    for i := 0; i < 3; i++ {
        fmt.Println("Enter animal name & query (eat / move / speak): ")
        var animal, op string
        if op == "eat" {
        } else if op == "move" {
        } else if op == "speak" {
        } else {

Command to run:

Directory where the GO file is present:/> go run (file_name).go

Valid test case 1:


Enter animal name & query (eat / move / speak): 

Enter animal name & query (eat / move / speak): 

Enter animal name & query (eat / move / speak): 



Invalid Test case 2:


Enter animal name & query (eat / move / speak): 

Enter animal name & query (eat / move / speak): 

Enter animal name & query (eat / move / speak): 


Invalid query entered!
Invalid query entered!

Visual demo on Linux terminal:

Class and Object in Golang

My Personal Notes arrow_drop_up
Recommended Articles
Page :