gpt4 book ai didi

go - 从函数约定 Golang 返回地址

转载 作者:行者123 更新时间:2023-12-01 22:36:35 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Stack vs heap allocation of structs in Go, and how they relate to garbage collection

(5 个回答)


2年前关闭。




编辑:请参阅附加的堆栈溢出问题。它准确地描述了我想要了解的内容,然后是一些:)

引用下面的代码,是返回变量的地址更好/标准化/约定,还是用地址创建变量?我知道无论哪种方式您都在修改相同的结构,但我想知道哪种方式更清洁?我也想知道这两种方式是否有任何优点/缺点。

type Thing struct {

}

func getThing() *Thing {
thing := Thing{}

// modify thing here

return &thing //return the address to the thing here
}

或者
type Thing struct {

}

func getThing() *Thing {
thing := &Thing{} //create the address to the thing here

//modify thing here

return thing
}

或者
type Thing struct {

}

func getThing() *Thing {
thing := new(Thing)

//modify thing here

return thing
}

最佳答案

如果你想使用方法修改结构然后&Thing{}是一个不错的选择。

例子:


type Thing struct {
data string
}

func (t Thing) Update1(data string){
t.data= data;
}

func (t *Thing) Update2(data string) {
t.data= data;
}

func getThing1() *Thing {
thing := Thing{}
thing.Update1("test") // don't update the data
return &thing
}

func getThing2() *Thing {
thing := &Thing{}
thing.Update2("test") // update the data
return thing
}

func main() {
now := getThing1()
fmt.Println(now.data) // it doesn't print anything
now = getThing2()
fmt.Println(now.data) // print "test"
}

关于go - 从函数约定 Golang 返回地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61465637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com