How to declare and access pointer variable in Golang?


Pointers are a powerful feature of Golang that allows developers to work with memory addresses directly. Pointers can be used to modify the values of a variable, pass a large data structure without copying it, and create linked data structures like linked lists. In this article, we'll discuss how to declare and access pointer variables in Golang.

Declaring a Pointer Variable

To declare a pointer variable in Golang, you use the * operator. The * operator tells Golang that the variable is a pointer, and not a regular value. Here's an example −

var p *int

In this example, we're declaring a pointer variable called p that will point to an integer. The *int part of the declaration tells Golang that p will be a pointer to an integer.

Initializing a Pointer Variable

When you declare a pointer variable in Golang, it's important to initialize it before using it. A pointer that has not been initialized is called a "nil" pointer, and it will cause a runtime error if you try to use it.

Here's how you can initialize a pointer variable in Golang −

var p *int
i := 42
p = &i

In this example, we declare a pointer variable called p that will point to an integer. We then declare an integer variable called i and set its value to 42. Finally, we set the value of p to the address of i using the & operator.

Accessing a Pointer Variable

Once you have a pointer variable in Golang, you can use the * operator to access the value it points to. Here's an example −

var p *int
i := 42
p = &i
fmt.Println(*p)

In this example, we declare a pointer variable called p that points to an integer. We then declare an integer variable called i and set its value to 42. Finally, we set the value of p to the address of i. When we print out the value of *p, Golang will follow the pointer and print out the value of i.

Updating the Value of a Pointer Variable

In Golang, you can use the * operator to update the value of the variable that a pointer points to. Here's an example −

var p *int
i := 42
p = &i
*p = 21
fmt.Println(i)

In this example, we declare a pointer variable called p that points to an integer. We then declare an integer variable called i and set its value to 42. Finally, we set the value of p to the address of i. When we set the value of *p to 21, Golang follows the pointer and updates the value of i. When we print out the value of i, it will be 21.

Conclusion

In this article, we've discussed how to declare and access pointer variables in Golang. Pointers are a powerful feature of the language that allows developers to work with memory addresses directly. By understanding how to use pointers, you can write more efficient and powerful Golang code.

Updated on: 05-May-2023

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements