iT邦幫忙

2021 iThome 鐵人賽

DAY 10
0
DevOps

"GoDevOps": Learn DevOps Tools with Go系列 第 10

[Golang] Pointer

Go provide pointer similar to C and C++.

  • Go use & operator to access the memory address of a variable.
  • The the value stored in the variable that the pointer points to can be accessed by the * 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)

Compare Two Pointer

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.")
}

Receiver Functions With Pointers

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)

}

上一篇
[Golang] Custom Type Declarations and Struct
下一篇
[Golang] Map
系列文
"GoDevOps": Learn DevOps Tools with Go11

尚未有邦友留言

立即登入留言