Sobes.tech
Middle

What is a pointer?

sobes.tech AI

Answer from AI

A pointer in Go is a variable that stores the address of another variable in memory. Pointers allow direct memory manipulation, changing variable values outside the current scope, and efficiently passing large structures without copying.

A pointer is declared using the * operator before the type, and the address of a variable can be obtained using the & operator.

Example:

package main
import "fmt"

func main() {
    var a int = 42
    var p *int = &a  // p is a pointer to a

    fmt.Println("Value of a:", a)       // 42
    fmt.Println("Address of a:", p)      // memory address
    fmt.Println("Value through pointer:", *p) // 42

    *p = 100  // change value of a through pointer
    fmt.Println("New value of a:", a) // 100
}

Thus, pointers allow more flexible and efficient data handling.