为什么我们在返回结构体而不是结构体指针时无法进行赋值?

huangapple go评论70阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2023年6月8日 21:12:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76432223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定