我的函数返回一个结构;为什么编译器不允许对该结果值的字段赋值? [英] My function returns a struct; why is assignment to a field of that result value disallowed by the compiler?
本文介绍了我的函数返回一个结构;为什么编译器不允许对该结果值的字段赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Golang中,如果我在函数中返回一个结构类型,我得到了编译错误,我必须使用结构的指针作为返回类型,通过函数调用直接实现成员访问。为什么会这样呢?Foo()不是返回Employee类型的临时变量吗?
package main
type Employee struct {
ID int
Name string
Address string
Position string
Salary int
ManagerID int
}
var dilbert Employee
func foo() Employee {
employee := Employee{}
return employee
}
func bar() *Employee {
employee := Employee{}
return &employee
}
func main() {
dilbert.Salary = 1
var b = foo()
b.Salary = 1
bar().Salary = 1 // this is good
foo().Salary = 1 // this line has the compilation error cannot assign to foo().Salary
}
推荐答案
在Go中,avariable是可寻址的,即可以获取其地址的值。如果左侧是可寻址的,则分配有效。
bar().Salary = 1
合法,因为
bar().Salary
实际上是(*bar()).Salary
的句法糖;*bar()
是可寻址的,因为它是间接指针;- 可寻址结构的字段(例如
Salary
)本身是可寻址的
相反,foo().Salary = 1
是非法的,因为foo()
返回值,但它不是变量,也不是间接指针;无法获得foo()
的地址。这解释了该语句被编译器拒绝的原因。请注意,引入中间变量可以解决您的问题:
// type and function declarations omitted
func main() {
f := foo()
f.Salary = 1 // compiles fine
}
这篇关于我的函数返回一个结构;为什么编译器不允许对该结果值的字段赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文