登录
首页 >  Golang >  Go问答

函数结果赋值

来源:stackoverflow

时间:2024-03-17 08:00:34 417浏览 收藏

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:

每个左侧操作数必须是 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?

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

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

理论要掌握,实操不能落!以上关于《函数结果赋值》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>