golang struct传值还是传地址?


之前用for range遍历slice,希望对slice每一项的struct值进行修改,但是最终修改失败。仔细考虑一下可能是go和js对Object的处理有差异,go传递的可能并不是引用(地址)

验证

首先验证一下函数传参的情况

type Node struct {
	id string
}

func test(node Node){
	log.Printf("%p", &node)
}

func main(){
	node := Node{
		id: "id",
	}
	log.Printf("%p", &node)     //0xc00003c1f0
	test(node)                  //0xc00003c210
}

地址果然不一样,可以初步确定,go函数传递struct时进行了拷贝

下面看一下for range的情况

type Node struct {
	id string
}


func main(){
	list := []Node{Node{id: "id"}}
	log.Printf("%p", &list[0])      //0xc00003c1f0
	for _, value := range list{
		log.Printf("%p", &value)    //0xc00003c210
	}
}

使用简单的的demo测试一下,显然range返回的value是对struct的拷贝,经常用js让我习惯性以为拿到的struct就是地址,使用pointer可以完全避免这个问题,这里记录一下这个小坑。


Author: Maple
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Maple !
  TOC