2012-11-23 19 views
0

我以爲我理解了Go的類和方法接收器,但顯然不是。他們一般工作直觀,但這裏的地方使用一個似乎引起「未定義:跆拳道」的例子錯誤:爲什麼指定Method Receiver有時會觸發'未定義'錯誤?

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

我現在用的是過去的一個月左右,並LiteIDE內golang下載的編譯器。請解釋!

回答

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() { 
} 
+0

回想起來,這些事情總是顯而易見,非常感謝。 – GregT

1

關於接收器的一點是,如果你想Wtf可以被調用,你必須調用與receiver.function()

它的功能,無需接收器,如果你想改變其聲明

func Wtf() { 

在不改變它的情況下調用它,你可以寫

Writeable{}.Wtf() 
+0

感謝您的幫助和快速回復。 – GregT

相關問題