为什么有时指定方法接收器会触发“未定义”错误?

huangapple go评论91阅读模式
英文:

Why does specifying a Method Receiver sometimes trigger an 'undefined' error?

问题

我以为我理解了Go的类和方法接收器,但显然不是这样。它们通常很直观,但是这里有一个例子,使用一个方法似乎会导致一个“undefined: Wtf”错误:

package main

type Writeable struct {
    seq int
}

func (w Writeable) Wtf() { // 这里会导致编译错误
//func Wtf() { // 如果你使用这个代替,它就能工作
}

func Write() {
    Wtf() // 这是编译器抱怨的那一行
}

func main() {
}

我使用的是最近一个月左右从golang下载的编译器,以及LiteIDE。请解释一下!

英文:

I thought I understood Go's classes and Method Receivers, but apparently not. They generally work intuitively, but here's an example where using one appears to cause an 'undefined: Wtf' error:

package main

type Writeable struct {
	seq int
}

func (w Writeable) Wtf() { // causes a compile error
//func Wtf() { // if you use this instead, it works
}

func Write() {
	Wtf() // this is the line that the compiler complains about
}

func main() {
}

I am using a compiler downloaded from golang within the last month or so, and LiteIDE. Please explain!

答案1

得分: 2

你正在将Wtf()定义为Writeable的一个方法。然后你试图在没有结构实例的情况下使用它。我修改了你的代码,创建了一个结构并将Wtf()作为该结构的方法使用。现在它可以编译通过。http://play.golang.org/p/cDIDANewar

package main

type Writeable struct {
    seq int
}

func (w Writeable) Wtf() { // 导致编译错误
//func Wtf() { // 如果你使用这个代替,它可以工作
}

func Write() {
    w := Writeable{}
    w.Wtf() // 这是编译器抱怨的那一行
}

func main() {
}
英文:

You're defining Wtf() as a method of Writeable. Then you're trying to use it without a struct instance. I changed your code below to create a struct and then use Wtf() as the method of that struct. Now it compiles. http://play.golang.org/p/cDIDANewar

package main

type Writeable struct {
    seq int
}

func (w Writeable) Wtf() { // causes a compile error
//func Wtf() { // if you use this instead, it works
}

func Write() {
    w := Writeable{}
    w.Wtf() // this is the line that the compiler complains about
}

func main() {
}

答案2

得分: 1

关于接收器的要点是,你必须使用receiver.function()的形式在其上调用函数。

如果你希望Wtf可以在没有接收器的情况下被调用,可以将其声明更改为

func Wtf() { 

如果你希望在不改变它的情况下调用它,可以写成

 Writeable{}.Wtf()
英文:

The point about the receiver is that you must call the function on it with receiver.function()

If you want Wtf to be callable without a receiver, change its declaration to

func Wtf() { 

If you want to call it without changing it, you may write

 Writeable{}.Wtf()

huangapple
  • 本文由 发表于 2012年11月24日 03:06:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/13534603.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定