GregT
GregT

Reputation: 1320

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

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!

Upvotes: 0

Views: 382

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382150

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

Upvotes: 1

Daniel
Daniel

Reputation: 38781

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

Upvotes: 2

Related Questions