Pointers in Go

The declartion of pointer in Go almost identical in C/C++. The BNF for pointer [1] is quotated below:

PointerType = "*" BaseType .
BaseType    = Type .

Unlike C/C++, the uninitialied point is set to nil by default.

Here is a quick example to show how to declare, use, and access pointers.

// go run pointer.go
package main
import "fmt"

func foo(p *int){
    *p = 1
}

func main(){
    var i int= 0;
    var p1 *int = &i
    var p2 *int = p1
    fmt.Println("The value pointed by p2 is", *p2)
    foo(p2)
    fmt.Println("After the function call, i is", i)
}

You should expect the following result:

The value pointed by p2 is 0
After the function call, i is 1

[1] https://golang.org/ref/spec#Pointer_types