go - 功能结果分配

标签 go

来自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/

相关文章:

go - Go slice 调整大小的不同表现

go - 从 interface{} 获取底层 reflect.Value

json - 使用 2 层深的元素解码 JSON

sql - 不支持的扫描,存储 driver.Value 类型

go - 如何在 Go/Golang 中使用 map[string]string 或自定义结构?

golang 模板 - 默认语义如何

go - Goroutine在 channel 上收听相同的结果

go - 如何使用银杏在多个测试文件中编写测试用例?

amazon-web-services - 向多个设备发送 SNS 推送通知消息

json - 在go lang中循环/迭代第二级嵌套JSON