“方法需要指示器接收器”在Go编程语言中 [英] "method requires pointer receiver" in Go Programming Language

查看:99
本文介绍了“方法需要指示器接收器”在Go编程语言中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚看到Go编程语言的演示文稿,并认为我会尝试写几行。一切工作正常,直到我试图在这种情况下使用接口。如何解决这个问题?

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)
}

我得到编译器错误:

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()会影响外部的enity功能。什么是我应该使用的语法?

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

推荐答案

我认为这里有一些困惑。 inc 是类型 *实体类型的方法,而不是类型 entity code>(虽然你可以直接在指针上调用值的方法,但你通常不能直接在指针上调用方法)。您可能会困惑的是为什么您可以调用 e.inc(),而不必执行(& e).inc() 。这是一个鲜为人知的特例,记录在语言的通话部分底部说明如果 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 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.

这篇关于“方法需要指示器接收器”在Go编程语言中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆