英文:
Why we cannot assign when we return a struct instead of pointer to struct?
问题
让我们假设我们有以下的结构体:
type Profile struct {
id int
name string
}
func test(p Profile) Profile {
return p
}
func main() {
var profile Profile
test(profile).id = 20 // 无法给test(profile).id赋值(类型为int的值)
}
但是如果我们将Profile
更改为*Profile
,作为test函数的返回类型,主函数就可以正常工作。
func test(p Profile) *Profile {
return &p
}
func main() {
var profile Profile
test(profile).id = 20 // 可以正常工作
}
为什么会出现这种情况呢?
英文:
Let's assume we have following struct
type Profile struct {
id int
name string
}
func test(p Profile) Profile {
return p
}
func main() {
var profile Profile
test(profile).id = 20 // cannot assign to test(profile).id (value of type int)
}
But if we change Profile
to *Profile
of the test function return type, main function works.
func test(p Profile) *Profile {
return &p
}
func main() {
var profile Profile
test(profile).id = 20 // Works
}
Why does this work like this?
答案1
得分: 1
将字段分配给Profile
的方式没有可观察的效果。您正在将值分配给一个(字段的)临时结构值,然后立即丢弃它。请注意,test的返回值是main中profile的副本的副本;它被复制到test的参数中,然后再从test返回时再次复制。
当返回一个指针时,指向的结构在赋值后仍然是可访问的,至少在原则上是这样(尽管在这种特定情况下不是这样,因为指针指向test的参数的副本)。
英文:
Assigning to a field of Profile
this way has no observable effect. You're assigning to a (field of a) temporary struct value that is then immediately discarded. Note that the return value of test is a copy of a copy of profile in main; it is copied to test's argument and then again when it is returned from test.
When returning a pointer, the struct pointed to is still accessible after the assignment, at least in principle (although not in this specific case because the pointer points to a copy of the argument to test).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论