“method requires pointer receiver” in Go Programming Language

后端 未结 2 1195
情书的邮戳
情书的邮戳 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:26

    Change it to: doSomething(&e). func (e *entity) inc() satisfies incer interface only for *entity type. There is no inc() for just entity type and that's what's you're passing to doSomething().

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题