了解GO中的指针
#go #指针

我们定义一个具有值和名称的变量。变量名称为converted to a memory address,该值存储在该地址中。如果有指针变量,则将另一个变量的实际存储地址存储为一个值。

two unary pointer operators

  • &用于获取变量的内存地址
  • *用于在指针变量存储的地址上获取值。

示例:

func main() {
    x := 7
    y := &x // creating a pointer variable

    p := fmt.Println
    pf := fmt.Printf

    pf("type of x (non pointer variable) = %T\n", x)
    p("value of x (stores actual data) =", x)
    p("address of x (memory address where x is located) =", &x)
    // invalid operation: cannot indirect x (variable of type int)
    // p("value dereferenced by x =", *x)

    p()
    pf("type of y (pointer variable) = %T\n", y)
    p("value of y (stores memory address of x) =", y)
    p("address of y (memory address where y is located) =", &y)
    p("value at the address stored by y (dereferencing the pointer) =", *y)
}

输出

type of x (non pointer variable) = int
value of x (stores actual data) = 7
address of x (memory address where x is located) = 0xc00001a0e8

type of y (pointer variable) = *int
value of y (stores memory address of x) = 0xc00001a0e8
address of y (memory address where y is located) = 0xc000012028
value at the address stored by y (dereferencing the pointer) = 7

资源:

  1. Passing by reference and value in Go to functions
  2. Reference (computer science)
  3. Pointer (computer programming)
  4. Pointer Operators
  5. How are variable names stored in memory in C?