亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang 結構的另一個 func 更改圖

golang 結構的另一個 func 更改圖

Go
慕容708150 2022-04-20 17:29:30
我是一個新人。現在我有一個關于函數傳遞變量的問題。這里是代碼:type User struct {    Name string    Map  map[string]string}func main() {    u := User{Name: "Leto"}    u.Map = make(map[string]string)    fmt.Println("before --------")    fmt.Println(unsafe.Pointer(&u))    fmt.Println(unsafe.Pointer(&(u.Map)))    fmt.Println(u)    Modify(u)    fmt.Println("after --------")    fmt.Println(u)}func Modify(u User) {    fmt.Println("in func --------")    fmt.Println(unsafe.Pointer(&u))    fmt.Println(unsafe.Pointer(&(u.Map)))    u.Name = "Paul"    u.Map["t"] = "t"}輸出上面的代碼:before --------0xc04203a4c00xc04203a4d0{Leto map[]}in func --------0xc04203a5000xc04203a510after --------{Leto map[t:t]}在修改功能中我知道用戶是一個副本,所以更改名稱不起作用是可以的,但是為什么將地圖效果更改為用戶結構?
查看完整描述

3 回答

?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

我們需要了解在每次調用中內存分配是如何工作的:


  u := User{Name: "Leto"}

// u is an object of type User

// after this line memory has been allocated to both the

// properties u.Name(string) and u.Map(reference)

// lets say allocated memory address for u.Name starts with x

// for u.Map it starts with y, and note that u.Map is a reference i.e. 

// the value contained in it will be a different memory address which

// will be the starting memory address of the actual map

// right now the value written at y is nil since it 

// does not point to any memory address

u.Map = make(map[string]string)

// now value of y has been updated to z (which is the 

// memory address of the beginning of the map initialized 

// with make call) 

fmt.Println("before --------")

fmt.Println(unsafe.Pointer(&u))

fmt.Println(unsafe.Pointer(&(u.Map)))

fmt.Println(u)

// here you are about to pass object by value 

// so basically a new object will be created of type User

// lets talk about how copy of this object will be created

// copy of u.Name will have a new address 

// lets call it x1 and the value "Leto" too will be 

// copied to memory address starting with x1

// copy of u.Map will have a new address too lets call it 

// y1 and its value z will be copied too to the memory address y1

// I think you must have got your answer by now. 

// Basically the newly copied object's property u.Map and 

// the old one's u.Map both points to the same memory address "z" 

// and hence whosoever updates the map the other one will see it

Modify(u)

fmt.Println("after --------")

fmt.Println(u)


查看完整回答
反對 回復 2022-04-20
?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

您應該在分配和修改操作中分別使用 &User 和 *User。

檢查這個https://play.golang.org/p/tDh1JBpK-t

使用指向結構的指針總是更好。


查看完整回答
反對 回復 2022-04-20
?
慕容森

TA貢獻1853條經驗 獲得超18個贊

切片、貼圖和通道是參考類型。所以它們總是通過引用傳遞。



查看完整回答
反對 回復 2022-04-20
  • 3 回答
  • 0 關注
  • 193 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號