【问题标题】:assignment of function result函数结果赋值
【发布时间】:2021-01-08 09:06:33
【问题描述】:

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

【问题讨论】:

  • 您希望employeeByID(10).Salary = 100 做什么?如果该函数返回 *Employee 是有意义的。
  • 出于同样的原因你不能做5 = 10。为什么要为本身不存储在任何地方的东西赋值?
  • C# 也做不到

标签: go


【解决方案1】:

它无法编译,因为该赋值无效。

Spec: Assignments:

每个左侧操作数必须是 addressable、映射索引表达式或(仅用于 = 赋值)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?

想一想:你调用一个函数,它返回一个值(你不存储它),如果你不存储结果,改变它会有什么好处?它将被丢弃,因此分配也将无用。

如果您将结果存储在第二个示例中的变量中,您可以更改其字段,因为变量是可寻址的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 2018-11-12
    • 2021-01-23
    • 1970-01-01
    相关资源
    最近更新 更多