“方法需要指针接收器”在 Go 编程语言中
我刚刚看到了 Go 编程语言的演示,并想尝试写几行。一切工作正常,直到我尝试在这种情况下使用界面。我该如何解决这个问题?
package main
import "fmt"
type entity float32
func (e *entity) inc() {
*e++
}
type incer interface {
inc()
}
func doSomething(i incer) {
i.inc()
}
func main() {
fmt.Println("Hello, 世界")
var e entity = 3
e.inc()
doSomething(e)
fmt.Println(e)
}
我收到编译器错误:
prog.go:24: cannot use e (type entity) as type incer in function argument:
entity does not implement incer (inc method requires pointer receiver)
我想使用指针,以便 inc() 影响函数外部的实体。我应该使用什么语法?
/瑞奇
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. How do I solve this?
package main
import "fmt"
type entity float32
func (e *entity) inc() {
*e++
}
type incer interface {
inc()
}
func doSomething(i incer) {
i.inc()
}
func main() {
fmt.Println("Hello, 世界")
var e entity = 3
e.inc()
doSomething(e)
fmt.Println(e)
}
I get the compiler error:
prog.go:24: cannot use e (type entity) as type incer in function argument:
entity does not implement incer (inc method requires pointer receiver)
I want to use a pointer so that the inc() will affect the enity outside the function. What is the syntax I should use?
/Ricky
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这里有些混乱。
inc
是*entity
类型的方法,而不是entity
类型的方法(虽然您可以直接在指针上调用值的方法;您通常不能直接在值上调用指针上的方法)。您可能会感到困惑的是为什么您可以调用e.inc()
,而不是必须执行(&e).inc()
。这是一个鲜为人知的特殊情况,记录在该语言的 Calls 部分的底部规范,表示如果x
是可寻址的,并且&x
的方法集包含m
,则xm() 是简写
(&x).m()
。这适用于这种情况,因为e
是一个变量,因此它是可寻址的;但其他表达式可能无法寻址。但是,我建议您不要使用此快捷方式,因为它会导致混乱;它让你认为e
符合接口inter
,但事实并非如此。I think there is some confusion here.
inc
is a method of the type*entity
, and not of the typeentity
(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 calle.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 ifx
is addressable, and&x
's method set containsm
, thenx.m()
is shorthand for(&x).m()
. This applies to this case becausee
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 thate
conforms to the interfaceinter
, while it does not.将其更改为:doSomething(&e)。 func (e *entity) inc() 仅满足 *entity 类型的 incer 接口。没有仅用于实体类型的 inc() ,这就是您传递给 doSomething() 的内容。
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().