【golog】我的go學與思7

指針

正文

package main

import "fmt"

func tmp() *int{
	v := 1
	return &v
}

func main() {
	i, j := 42, 2701

	p := &i         // point to i
	fmt.Println(*p) // read i through the pointer
	*p = 21         // set i through the pointer
	fmt.Println(i)  // see the new value of i

	p = &j         // point to j
	*p = *p / 37   // divide j through the pointer
	fmt.Println(j) // see the new value of j
	fmt.Println(tmp() == tmp(),*tmp())
}

//輸出
42
21
73
false 1

這裏和c++很相似,都有取址。但是p++這樣的指針運算是非法的。

最讓我費解的是返回臨時變量的地址,每次不相同,但是都是對的。這邊有點想不明白go的內存模型了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章