Class and Object in Golang
Last Updated :
10 Nov, 2022
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 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 from 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 the 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.
Go
package main
import (
"fmt"
)
type Animaler interface {
Eat()
Move()
Speak()
Error()
}
type SuperAnimals struct {
locomotion string
}
type Animals struct {
SuperAnimals
food string
sound string
}
func (x Animals) Eat() {
fmt.Println(x.food)
}
func (x Animals) Move() {
fmt.Println(x.locomotion)
}
func (x Animals) Speak() {
fmt.Println(x.sound)
}
func (x Animals) Error() {
fmt.Println( "Invalid query entered!" )
}
func main() {
m := map [ string ]Animaler{
"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): " )
fmt.Print( ">" )
var animal, op string
fmt.Scan(&animal)
fmt.Print( ">" )
fmt.Scan(&op)
if op == "eat" {
m[animal].Eat()
} else if op == "move" {
m[animal].Move()
} else if op == "speak" {
m[animal].Speak()
} else {
m[animal].Error()
}
}
}
|
Command to run:
Directory where the GO file is present:/> go run (file_name).go
Valid test case 1:
Input:
Enter animal name & query (eat / move / speak):
>snake
>move
Enter animal name & query (eat / move / speak):
>bird
>eat
Enter animal name & query (eat / move / speak):
>cow
>speak
Output:
slither
worms
moo
Invalid Test case 2:
Input:
Enter animal name & query (eat / move / speak):
>snake
>drink
Enter animal name & query (eat / move / speak):
>cow
>eat
Enter animal name & query (eat / move / speak):
>dog
>talk
Output:
Invalid query entered!
grass
Invalid query entered!
Visual demo on Linux terminal:

Similar Reads
Closures in Golang
Go language provides a special feature known as an anonymous function. An anonymous function can form a closure. A closure is a special type of anonymous function that references variables declared outside of the function itself. It is similar to accessing global variables which are available before
2 min read
Channel in Golang
In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. Or in other words, a channel is a technique which allows to let one goroutine to send data to another goroutine. By default channel is bidirectional, means the gor
7 min read
Generics in Golang
Generics are essentially template/boilerplate code written in a form to use on the Go with types that can be added later. The main aim of generics is to achieve greater flexibility in terms of writing code with the addition of fewer lines. The concept of Generics has existed for a long time now and
4 min read
Type Assertions in Golang
Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specifie
2 min read
main and init function in Golang
The Go language reserve two functions for special purpose and the functions are main() and init() function. main() functionIn Go language, the main package is a special package which is used with the programs that are executable and this package contains main() function. The main() function is a spe
2 min read
Atomic Variable in Golang
In Go language, Atomic Variables are utilized in order to control state. Here, the "sync/atomic" package must be used to use these variables. Moreover, it also prevents race conditions which allows two or more Goroutines to access identical sources. The Atomic counters are available for several goro
3 min read
Anonymous Structure and Field in Golang
In Golang, structures (or structs) allow us to group elements of various types into a single unit, which is useful for modeling real-world entities. Anonymous structures are unnamed, temporary structures used for a one-time purpose, while anonymous fields allow embedding fields without names. Exampl
3 min read
Basics of JSON with GoLang
JSON is a widely used format for data interchange. Golang provides multiple encoding and decoding APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. Data Types: The default Golang data types for decoding and encoding JSON are as follows: bool
3 min read
Pointer to a Struct in Golang
In Go, structs are used to create custom data types that group different fields together. When working with structs, using pointers can be especially beneficial for managing memory efficiently and for avoiding unnecessary copying of data. A pointer to a struct allows you to directly reference and mo
3 min read
Reflection in Golang
Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose. Reflection is often termed as a method of metaprogramming. To und
6 min read