Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024

Go Pointers & Methods

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Golang is syntactically similar to C, and it is similarly straightforward, clean, and efficient. If you're familiar with C concepts, golang's fundamentals are clear to understand.

Golang is an easy-to-learn programming language. Anyone who understands the fundamentals of programming can pick up the basics in a few hours. Due to its simplicity, the entire language specification is only a few pages long.

Because pointers and methods are some of the most basic and fundamental ideas in Golang, it is critical to understand them in order to grasp the language properly.

In this blog, we will discuss more about pointers and methods in Golang. 

Pointers in Golang

In the Go programming language (also known as Golang), a pointer is a variable that stores the memory address of another variable. In Golang, pointers are also known as special variables. The variables are used to store data in the system at a specific memory address. They are represented in hexadecimal notations. 

First, we need to understand the concept of variables before understanding the need for pointers. 

Variables are the identifiers provided to the memory locations where the data is actually stored. The address of that particular memory region is required to access the stored data. Manually remembering all of the memory locations (Hexadecimal Format) is inefficient, which is why we store data in variables, which can be retrieved simply by typing their name.

A hexadecimal number may also be saved into a variable in Golang using the literal expression, i.e., any integer starting with 0x is a hexadecimal number.

A pointer is a type of variable that not only stores the memory addresses of other variables but also refers to the memory location and offers methods for determining the value stored there. It's known as a Special Kind of Variable because it's nearly like a variable, except it's preceded by a *. (dereferencing operator).

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Pointer Operators

  • &(address operator): This operator returns the address of the variable
  • *(dereferencing operator): It is used for two purposes. It is used to declare pointer type variables and also to get the value stored in the address pointed by the pointer. 

Syntax to declare a pointer

var pointerName *data_type

 

Initializing a pointer

var varInt int = 10
var varPtr *int = &varInt

 

Example

package main

import "fmt"

func main() {

var varInt int = 10
var varPtr *int = &varInt
fmt.Println("Value of varInt ", varInt)
fmt.Println("Address of varInt ", &varInt)
fmt.Println("Value of varPtr", varPtr)
}

 

Output:

Value of varInt  10
Address of varInt  0xc000018030
Value of varPtr 0xc000018030

 

You can clearly see from the above example that the content of the varPtr and the address of varInt are the same. 

Methods in Golang

The only distinction between Go methods and Go functions is that the method has a receiver parameter. The method may access the receiver's properties with the help of the receiver parameter. The receiver can be either struct or non-struct in this case. The receiver and receiver type must be in the same package when creating a method in your code. Furthermore, you are not permitted to create a method whose receiver type is already specified in another package, including built-in types such as int, string, and so on. If you try to do so, you'll get an error from the compiler.

 

Syntax:

func(reciver_name Type) method_name(parameter_list)(return_type){
}

 

Now let us see different types of receivers.

Struct receiver

In the Go programming language, you may construct a method whose receiver is a struct type. As illustrated in the sample below, this receiver is available within the method:

 

Example:

package main
 
import "fmt"
 
type pen struct {
    name      string
    company    string
    price int
}

func (penStruct pen) details() {
    fmt.Println("Pen Name: ", penStruct.name)
    fmt.Println("Pen company: ", penStruct.company)
    fmt.Println("Pen price: ", penStruct.price)
}
 
func main() {
    penStruct := pen{
        name:      "trimax",
        company:    "reynolds",
        price: 40,
    }
   
    penStruct.details()
}

 

Output:

Pen Name:  trimax
Pen company:  reynolds
Pen price:  40

 

As you can see from the example above, we passed the pen object into the function named details, and we were able to access its attributes from inside the function.

Non-Struct receiver

You can build a method with a non-struct type receiver in the Go language as long as the type and method descriptions are in the same package. If they are declared in distinct packages, such as int, string, and so on, the compiler will complain since they are defined in different packages.

 

Example:

package main
 
import "fmt"
 
type information string

func (d1 information) concatenation(d2 information) information {
    return d1 + d2
}
 

func main() {
    value1 := information("ab")
    value2 := information("cd")
    concat := value1.concatenation(value2)
    fmt.Println("Result: ", concat)
}

 

Output:

Result:  abcd

Pointer receiver

You may build a method with a pointer receiver in the Go programming language. If a change is made to it in a method using a pointer receiver, it will be reflected in the caller, which is not possible with value receiver methods.

 

Example:

package main

import "fmt"

type pen struct {
    name    string
    company string
    price   int
}

func (penStruct *pen) changePrice(newPrice int) {
    (*penStruct).price = newPrice
}

func main() {

    // Initializing the values
    // of the pen structure
    penStruct := pen{
        name:    "writer",
        company: "comp",
        price:   100,
    }

    fmt.Println("Pen name: ", penStruct.name)
    fmt.Println("Original Price ", penStruct.price)

    pointerToPen := &penStruct

    pointerToPen.changePrice(200)
    fmt.Println("Pen name: ", penStruct.name)
    fmt.Println("Final Price ", penStruct.price)
}

 

Output:

Pen name:  writer
Original Price  100
Pen name:  writer
Final Price  200

Pointer vs Value Reciever

Use a pointer receiver if you wish to modify the state of the receiver in a method by changing its value. With a value receiver that copies by value, this isn't possible. Any changes made to a value recipient are only applied to that copy. Use a value receiver if you don't need to change the receiver value.

On each method call, the Pointer recipient avoids copying the value. If the receiver is a huge struct, this can be more efficient. Value receivers are concurrency safe, but pointer receivers are not. As a result, a programmer must take care of it.

FAQs

  1. What are pointers in golang?
    In the Go programming language, a pointer is a variable that stores the memory address of another variable. In Golang, pointers are also known as special variables. These variables are used to store data in the system at a specific memory address.
     
  2. How to define a function in golang?
    The func keyword is used to define a function. This is followed by choosing a function name and a set of parentheses containing any parameters that the function will accept.

     
  3. What is the difference between function and methods in golang?
    Methods and functions are essentially the same except for the fact that methods contain a receiver, but functions do not. 

Key Takeaways

In this article, we have extensively discussed functions & methods and their implementation in the Go programming language. We hope that this blog has helped you enhance your knowledge regarding functions & methods and if you would like to learn more, check out our articles on GoLang. Do upvote our blog to help other ninjas grow. 

Happy Coding!

Topics covered
1.
Introduction
2.
Pointers in Golang
3.
Pointer Operators
4.
Methods in Golang
5.
Struct receiver
6.
Non-Struct receiver
7.
Pointer receiver
8.
Pointer vs Value Reciever
9.
FAQs
10.
Key Takeaways