dtbsezxw28056 2017-11-23 16:26
浏览 58
已采纳

通过引用实例化对象

Here is a sample of Go code which I do not really understand:

type MyClass struct {
    field1      string
    field2      string
}
...
objectinstance1 := MyClass{field1:"Hello", field2:"World"}
objectinstance2 := &MyClass{field1:"Hello", field2:"World"}

I can do exactly the same thing with objectinstance1 and objectinstance2 (method call for example) with the same syntax.

So I do not understand the role of the & operator. What I understand is that objectinstance1 contains an object whereas objectinstance2 contains a pointer.

It is for me the same thing in C than the difference between char and char*.

But in this case I should use -> instead of . (dot)?

  • 写回答

4条回答 默认 最新

  • dougan6402 2017-11-23 18:45
    关注

    Difference is not visible because it’s hidden in 2 things:

    1. Operator := which assigns value and type for a variable simultaneously. So it looks like objectinstance1 and objectinstance2 are the same. But in fact first is a MyClass instance and second is a pointer to it. It will be more palpable if use long-form operator:

      var objectinstace1 MyClass = MyClass{} var objectinstance2 *MyClass = &MyClass{}

    If you omit * or & variable and type become incompatible and assignment fails.

    1. Implicit pointer indirection. Go does it automatically in statements like ptr1.Field1 to access a specific field in struct by pointer to it.

      Only on rare cases when there’s ambiguity you have to use full form:

      *ptr1.Value1

      or sometimes even:

      (*ptr1).Value1

    UPDATE:

    Explicit pointer usage for disambiguation:

    type M map[int]int
    
    func (m *M) Add1() {
        // this doesn't work -  invalid operation: m[1] (type *M does not support indexing)
        // m[1] = 1
    
        // the same - invalid operation: m[1] (type *M does not support indexing)
        // *m[1] = 1
    
        // this works
        (*m)[1] = 1
    }
    

    https://play.golang.org/p/JcXd_oNIAw

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改