douchigu1723 2011-09-15 22:47
浏览 79
已采纳

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

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

  • 写回答

2条回答 默认 最新

  • duanji1899 2011-09-16 00:29
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++ 如何判断设置快捷键来实现隐藏/显示窗口
  • ¥15 关于#材料工程#的问题:有没有具有电子阻挡层和空穴阻挡层的电池仿真silvaco代码例子或者其他器件具有阻挡层例子的silvaco代码(最好还有相关文献)
  • ¥60 基于MATLAB的TAOD算法
  • ¥15 Groimp使用疑问
  • ¥15 MDK–ARM里一直找不到调试器
  • ¥15 oracle中sql查询问题
  • ¥15 vue使用gojs3.0版本,在nodeDataArray中的iconSrc使用gif本地路径,展示出来后动画是静态的,不是动态的
  • ¥100 代写个MATLAB代码,有偿
  • ¥15 ansys electronics 2021 R1安装报错,错误代码2,如图
  • ¥15 Dev-c++打字不出现中文,但出现日文