Cyberithub

How to Use Methods in Golang [Explained with Best examples]

Advertisements

In this tutorial, we will see how to use methods in Golang with the help of best examples in detail. Go does not directly support Object Oriented Programming (OOP) since it does not possess classes. But object oriented code can be written in Go using a combination of structs, methods and interfaces. In this article, we will explore methods in Go, what they mean and how they help to write object oriented code in Go.

 

Prerequisites

In order to follow through this article:-

Advertisements
  • You need to have a basic understanding of programming.
  • You need to download the Go compiler from the official website and follow the directions to install it based on your operating system being either Windows, MacOS or any of the Linux distributions.
  • You need a code editor like visual studio, atom or sublime text. Alternatively, you can download an Integrated Development Environment (IDE). An IDE is an improved code editor with added qualities customized to help you write and execute codes easier. JetBrains Goland is the most popular IDE used for developing Go programs.
  • You need to have an understanding of Go basic data types, aggregate data types, pointers and how to run Go programs.

 

How to Use Methods in Golang [Explained with Best examples]

How to Use Methods in Golang [Explained with Best examples]

Also Read: Functions in Golang with Examples [Complete Tutorial]

Go does not have the concept of classes, but structs in Go can technically be compared to classes in other languages. Methods allow you to associate a function to a defined struct type (or any type defined in the same package) just like classes allow in other OOP languages.

Advertisements

Methods in Go are like functions, but they are declared with a receiver type before the function name. A method’s receiver type is a type declared in the same package as the method, therefore inbuilt types like int, string and float64 cannot be directly declared as receiver types. A type alias can be used to associate a method to a type defined in another package. Methods are defined in the format below.

func  (receiver_name  Receiver_type)  method_name(parameters)  return_type {
// Method_body

Advertisements

}

NOTE:

Advertisements
Please note that all code samples in this article were run on a 64-bit Ubuntu 20.04 Linux environment.

How to Use Methods in Golang [Explained with Best examples] 2

Output

How to Use Methods in Golang [Explained with Best examples] 3

A method receiver is like an extra parameter passed into a function, but the receiver associates itself with the function. Except in peculiar cases, methods are usually defined with struct type receivers. The fields of the struct receiver can be accessed from within the function as shown below:-

How to Use Methods in Golang [Explained with Best examples] 4

Output

How to Use Methods in Golang [Explained with Best examples] 5

Go allows you to assign the receiver a name, like a function parameter. But as a matter of convention, the receiver name is usually assigned the lower case first letter of the receiver type. In the example above, we used the name p which is from the type Person.

Methods associate a function to a receiver type. Therefore, multiple methods with the same name and signature are different if they have different receiver types. When a method is called, the compiler checks the receiver type to determine what method should be run. Let’s see a brief example showing this behaviour.

How to Use Methods in Golang [Explained with Best examples] 6

How to Use Methods in Golang [Explained with Best examples] 7

Output

How to Use Methods in Golang [Explained with Best examples] 8

In the snippet above, Car and Person are two types that both possess the Print() method. On line 42, a Print() method is called with a variable of type Person, therefore the Print() method on lines 20-25 is run. But on line 51 , a Print() method with a variable of type Car is called, therefore, the method on lines 27-32 is run.

 

Value Receiver

In the examples above, we defined the receiver types as a value receiver. This means that the method receives a copy of the receiver variable with every call to it. With a value receiver, the method won’t be able to affect the caller variable. Let’s see a brief example to demonstrate this behaviour.

How to Use Methods in Golang [Explained with Best examples] 9

Output

How to Use Methods in Golang [Explained with Best examples] 10

Go allows you to use a pointer type to call a method defined with a value type. The compiler implicitly dereferences the pointer, creates a copy of the variable's value and passes it into the method. From the code snippet above, if we call SetPrice and Print with a pointer variable, the compiler executes it correctly. The output will be the same as the output above.

How to Use Methods in Golang [Explained with Best examples] 11

Output

How to Use Methods in Golang [Explained with Best examples] 12

 

Pointer Receiver

Go allows you to define a method with a pointer receiver. This allows the method to be able to modify the caller variable. We use a pointer variable when the method needs to make changes to a caller variable.

How to Use Methods in Golang [Explained with Best examples] 13

Output

How to Use Methods in Golang [Explained with Best examples] 14

Pointer receivers also work similarly to value receivers. A value variable of type T can be used to call a method defined with type *T. The compiler implicitly gets the address of the variable and passes it into the method. Therefore, any change made to the receiver within the method will affect the caller variable.

How to Use Methods in Golang [Explained with Best examples] 15

Output

How to Use Methods in Golang [Explained with Best examples] 16

As a convention, it is advised to define all methods of a given type as using either pointer or value receiver. Regardless if a method needs to make a change to the receiver variable, defining all methods as a single type allows the code to be more uniform and readable.

 

Method Values

Methods are also like functions since they can be treated as values. By omitting the parentheses when calling a method, we can assign the method to a variable. The variable then becomes a function that needs only its parameters. The variable can now be passed into functions, received from functions, or called with its parameters. I know this is quite confusing, so let’s look at a brief example to explain how it works.

How to Use Methods in Golang [Explained with Best examples] 17

Output

How to Use Methods in Golang [Explained with Best examples] 18

 

Method Expressions

Method expressions are a way to convert methods into functions, and a method receiver into a function parameter. By assigning a variable to the receiver type and method, separated by a dot (.), the variable becomes a function that takes a first argument of the receiver type. The parameters defined from the method declaration are passed in after the receiver argument. Let’s see an example to demonstrate how method expressions work.

How to Use Methods in Golang [Explained with Best examples] 19

Output

How to Use Methods in Golang [Explained with Best examples] 20

Method expressions can be applied where you have various methods for a single type and need to determine which method to run with many receivers. In this case, you can use an assertion to determine which method to create a method expression for, then pass in the various receiver values as parameters.

 

Composition

Composition is a fundamental concept in OOP. It refers to a class instance that is made up of other class instances. In Go, structs with methods behave like classes. We can achieve composition in Go by a concept known as struct embedding. Struct embedding refers to embedding an anonymous struct into another struct. This allows the embedding struct to inherit the same behaviour as the embedded struct. Let's demonstrate this with an example below.

How to Use Methods in Golang [Explained with Best examples] 21

How to Use Methods in Golang [Explained with Best examples] 22

Output

How to Use Methods in Golang [Explained with Best examples] 23

The example above is a program that determines if a car is fast based on its engine wheel drive. Since an engine is a property of a car, the engine struct is embedded within car. IsFast() is a method defined on the type engine, but we in the snippet above, we call IsFast() on the variable mercedes which is of type car. This concept is called composition. We can override the composition by defining an IsFast() method for the type car.

 

Encapsulation

Encapsulation is another important concept in OOP. It involves hiding direct access of an object from external clients. Go uses the implementation of capitalising the first letter of a type, function, struct or field of a struct to export it. So we can encapsulate each of functions, types, structs or fields by starting it with a lower case, thereby making it private and accessible only within the package it is declared.

Encapsulation in Go involves making a data private by embedding it within an exported struct without exporting its field. This ensures that the data cannot be assigned a value arbitrarily by a client. You can then use methods to read or update the data. This ensures that the data maintains its internal invariants. Methods used to read and update encapsulated data are called getters and setters respectively.

How to Use Methods in Golang [Explained with Best examples] 24

In the snippet above, we create a new package count. We declare an exported struct Count with an unexported field num. Then we define a getter method Num to return the value stored in num at a time, and we define a setter method Increment to increment num based on an offset. This way, the creator of the package is able to control how a client can interact with the Count object. We also define the Reset method to reset num to zero. If we import the count package into main, we will not be able to assign a value to num directly, instead, we will be able to use the setter and getter methods to control num.

How to Use Methods in Golang [Explained with Best examples] 25

Output

How to Use Methods in Golang [Explained with Best examples] 26

 

Conclusion

Declaring methods is ultimately similar to declaring functions in Go except that the functions are associated to a defined type. Methods can be called with both pointer and value receivers regardless of the type it was defined with, this is another distinguishing feature with functions. Grouping methods into what is called an interface allows you to write completely object oriented code which is readable and maintainable.

Leave a Comment