go为什么不能实例化对象之后,立即调用对象的方法?

萌新go。想问个问题:

为什么这样写可以

    a := StringClass{}
    a.HasValue(this.identityNo)

这样写不可以(提示无法在 'StringClass{}' 中调用指针方法

b := StringClass{}.HasValue(this.identityNo)

一定要定义,和使用,分开来写吗?

阅读 1.5k
1 个回答

tldr: 不能在结构体字面量上调用 receiver 为指针的方法。


Calls

A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m():

Addressable

For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal.

composite literal 并非 addressable ,所以不能直接调用 receiver 为指针的方法。

但是,可以用 (&stringClass{}).foo() 。因为作为一个特例,& 可以作用于 composite literal 。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题