create a pointer in go

In Go, a pointer is a variable that holds the memory address of another variable. Pointers are used to pass memory addresses between functions or to share data between multiple functions or goroutines.

To create a pointer in Go, you can use the & operator followed by the variable you want the pointer to reference. Here is an example:

main.go
package main

import "fmt"

func main() {
    var x int = 10
    var ptr *int = &x

    fmt.Println("Value of x:", x) // prints 10
    fmt.Println("Address of x:", &x) // prints address of x
    fmt.Println("Value of ptr:", ptr) // prints address of x
    fmt.Println("Value pointed to by ptr:", *ptr) // prints 10

    *ptr = 20 // change the value of x using the pointer

    fmt.Println("Value of x:", x) // prints 20
}
423 chars
18 lines

In this example, we declare a variable x with an initial value of 10. We then declare a pointer ptr of type *int (pointer to an integer) and initialize it to the memory address of x using the & operator.

To access the value pointed to by the pointer, we use the * operator. We can also modify the value of the original variable by indirectly referencing it through the pointer using the * operator.

Note that Go has no pointer arithmetic like C or C++, which means you cannot use pointers to iterate through an array or perform other pointer arithmetic operations.

gistlibby LogSnag