“method requires pointer receiver” in Go Programming Language

后端 未结 2 1196
情书的邮戳
情书的邮戳 2021-02-02 13:56

I just saw a presentation of the Go programming language and thought I\'d try to write a few lines. Everything worked fine until I tried to use an interface in this situation. H

2条回答
  •  温柔的废话
    2021-02-02 14:30

    I think there is some confusion here. inc is a method of the type *entity, and not of the type entity (while you can call methods on values directly on pointers; you cannot generally call methods on pointers directly on values). What you may be confused about is why you could call e.inc(), instead of having to do (&e).inc(). This is a little-known special case documented at the bottom of the Calls section in the language specification, that says if x is addressable, and &x's method set contains m, then x.m() is shorthand for (&x).m(). This applies to this case because e is a variable, so it is addressable; but other expressions may not be addressable. I would recommend that you not use this shortcut, however, as it causes confusion; it makes you think that e conforms to the interface inter, while it does not.

提交回复
热议问题