douhong4452 2015-11-22 03:06
浏览 49
已采纳

指针/非指针类型的结构字段分配差异

In section 4.4 (Structs) of The Go Programming Language, there is a code excerpt:

var dilbert Employee
func EmployeeByID(id int) *Employee { /* ... */ }
id := dilbert.ID
EmployeeByID(id).salary = 0

with the remark

If the result type of EmployeeByID were changed to Employee instead of *Employee, the assignment statement would not compile since its left-hand side would not identify a variable.

I don't understand why changing the result type of EmployeeByID to Employee would cause LHS not identify a variable.

  • 写回答

3条回答 默认 最新

  • duancheng7743 2015-11-22 03:48
    关注

    This simplified example demonstrates the issue:

    package main
    
    type t struct {
        int
    }
    
    func newT() *t { return &t{} }
    //func newT() t { return t{} }
    
    func main() {
        newT().int = 0
    }
    

    My guess is that if you use the version of newT that does not return a pointer, and never save off a reference to the result of newT(), then setting the value of its int field can never meaningfully do anything. It's similar to setting an unused variable.

    If instead you the non-pointer version of newT but you have something like:

    x := newT()
    x.int = 0
    

    Then you'd be fine.

    Alternatively, using the pointer version of newT above is fine, because it could be returning some state you already had defined previously, see example:

    package main
    
    type t struct {
        int
    }
    
    var dilbert = &t{3}
    
    func newT() *t { return dilbert }
    
    //func newT() t { return t{} }
    
    func main() {
        println(dilbert.int)
        newT().int = 0
        println(dilbert.int)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值