create a pointer to a pointer in go

In Go, a pointer is a variable that stores the address of another variable. We can create a pointer to a pointer, also known as a double pointer, by declaring another pointer variable that stores the address of the original pointer variable.

Here's an example of how to create a pointer to a pointer in Go:

main.go
package main

func main() {
    var x int = 10          // original variable
    var p1 *int = &x        // pointer to the original variable
    var p2 **int = &p1      // pointer to the pointer to the original variable

    println("Value of x:", x)
    println("Value of p1:", *p1)     // dereferencing p1 should give us x's value
    println("Value of p2:", **p2)    // dereferencing p2 twice should also give us x's value
}
428 chars
12 lines

In this example, we first declare an integer variable x with the value of 10. We then declare a pointer to x called p1 by using the & operator to get the address of x.

Next, we declare a pointer to a pointer to x called p2 with the ** notation. We set p2 to the address of p1 by using the & operator again.

Finally, we print out the values of x, p1, and p2. We use the * operator to dereference p1 and ** to dereference p2 twice. Dereferencing p1 gives us the value of x, and dereferencing p2 twice also gives us the value of x.

Output:

main.go
Value of x: 10
Value of p1: 10
Value of p2: 10
47 chars
4 lines

gistlibby LogSnag