Go provide pointer similar to C and C++.
&
operator to access the memory address of a variable.*
operator.For example:
var a int = 10
// declre a pointer that store the memory address of int variables.
// var p1 *int = &a
p1 := &a
// You can use 'new()' funtion to decalir a pointer as well
p2 := new(int)
p2 = &a
fmt.Println(a)
fmt.Println(p1)
fmt.Println(p2)
fmt.Println(*p1)
fmt.Println(*p2)
// Dereferencing. update the value that the pointer point to.
*p1 = 100
fmt.Println(a)
fmt.Println(p1)
fmt.Println(p2)
fmt.Println(*p1)
fmt.Println(*p2)
You can compare two pointers of same type using operators ==
, <
or >
.
if p1 == p2 {
fmt.Println("Both pointers p1 and p2 point to the same variable.")
}
In a normal receiver functions, the parameters are pass by value.
With the feature of pointer, Go can pass the parameters by address
type player struct {
name string
coins int
}
func (p1 *player) giveCoinsTo(p2 *player, payCoins int) {
(*p1).coins = (*p1).coins - payCoins
(*p2).coins = (*p2).coins + payCoins
}
func main() {
a := player{name: "Brandon", coins: 1000}
b := player{name: "James", coins: 5000}
// declre pointers to these two players
p1 := &a
p2 := &b
p1.giveCoinsTo(p2, 300)
fmt.Println(a.coins)
fmt.Println(b.coins)
}