What is a pointer in Go? How do you use it?

What is a pointer in Go? How do you use it? post thumbnail image

A pointer is a variable that stores the memory address of another variable in Go. Pointers are useful when you want to pass large data structures to a function without incurring the overhead of copying the entire structure. They also allow you to modify the original variable directly from within a function.

In Go, you can declare a pointer by using the * operator followed by the variable type. Here’s an example:





var count int = 42
var ptr *int = &count // declaring a pointer to the `count` variable
fmt.Println(*ptr) 

In this example, we first declare an integer variable count and assign it the value 42. We then declare a pointer variable ptr of type *int and assign it the memory address of count using the & operator.

To access the value of the variable that ptr points to, we use the * operator to dereference the pointer. The expression *ptr gives us the value stored at the memory address that ptr points to, which is the value of the count variable.

Pointers can also be passed as arguments to functions. Here’s an example:

func increment(ptr *int) {
    *ptr++
}

func main() {
    var count int = 42

    increment(&count) // passing the address of `count` to the `increment` function

    fmt.Println(count) // prints 43
}

In this example, we define a function increment that takes a pointer to an integer as an argument. Inside the function, we use the * operator to dereference the pointer and increment the value of the integer.

In the main function, we declare an integer variable count and assign it the value 42. We then pass the address of count to the increment function using the & operator. This allows the increment function to modify the value of count directly. After the function call, we print the value of count, which is now 43.

Leave a Reply

Your email address will not be published. Required fields are marked *

7 + 1 =

Related Post