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)
}
<<: Day 16 分享一下研究 Compose UI 到目前的心得
前言 今天来到第 20 天! 然後仍然是 Codecademy 学 React 系列, 今天进度是 ...
今天,要来介绍Fragment(片段),它是Activity中的一部分,一个Activity可能有数...
前言 昨天讲过了远古时代的记忆体管理,跟後续为了解决最古老的记忆体管理所引发的问题而接着有的分段管理...
Filebeat是用於转发和集中日志数据的轻量级传送程序。作为服务器上的代理安装,Filebeat监...
前面我们已经介绍完 FlowFiles 了,接下来就是可以一步一步地去建置我们的 Data Pipe...