来自C#,这使我感到困惑。
在Go中,如果我有
type Employee struct {
ID int
Salary int
}
那我就可以var tom Employee
tom.Salary = 100
到目前为止,一切都很好。那如果我有一个功能func employeeByID(id int) Employee {
// do something and return an employee
}
那为什么不编译呢?employeeByID(10).Salary = 100
此外,这似乎可以编译:andrew := employeeByID(10)
andrew.Salary = 100
最佳答案
由于该分配无效,因此无法编译。
Spec: Assignments:
Each left-hand side operand must be addressable, a map index expression, or (for = assignments only) the blank identifier.
函数调用的返回值不可寻址。有关详细信息,请参见How to get the pointer of return value from function call?和How can I store reference to the result of an operation in Go?。
想想看:调用一个函数,它返回一个值(不存储),如果不存储结果,更改它会有什么好处?它会被丢弃,因此分配也将是无用的。
如果像第二个示例一样将结果存储在变量中,则可以更改其字段,因为变量是可寻址的。
关于go - 功能结果分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65626120/