我以为我理解了Go的课程和方法接收者,但显然不是。它们通常直观地工作,但是这里有一个示例,其中使用一个似乎导致'undefined:Wtf'错误:
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() {
}
我使用的是在过去一个月左右从golang下载的编译器,以及LiteIDE。请解释一下!
答案 0 :(得分:2)
您将Wtf()定义为可写方法。然后你在没有结构实例的情况下尝试使用它。我更改了下面的代码来创建一个结构,然后使用Wtf()作为该结构的方法。现在它编译。 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() {
}
答案 1 :(得分:1)
关于接收器的要点是你必须用receiver.function()
如果您希望在没有接收器的情况下调用Wtf
,请将其声明更改为
func Wtf() {
如果你想在不改变的情况下调用它,你可以写
Writeable{}.Wtf()