Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement _() method?

I found an interface with a method called _ in it. I tried implementing it, but it's not working:

package main
func main() {}

func ft(t T) { fi(t) }
func fi(I) {}

type I interface {
    _() int
}

type T struct {}

func (T) _() int { return 0 }
func (T) _(int) int { return 0 }

$ go run a.go 
./a.go:4: cannot use t (type T) as type I in function argument:
  T does not implement I (missing _ method)

I also tried adding the overloaded method _(int) but that's not working either:

package main
func main() {}

type I interface {
    _() int
    _(int) int
}

type T struct {}

func (T) _() int { return 0 }
func (T) _(int) int { return 0 }

$ go run a.go 
# command-line-arguments
./a.go:12: internal compiler error: sigcmp vs sortinter _ _

Why? What is the purpose of this _ method? I think it might be a way to prevent people from implementing the interface (like private interfaces in Java)?

like image 308
Dog Avatar asked Aug 23 '14 21:08

Dog


1 Answers

_ is the "blank identifier" (https://golang.org/ref/spec#Blank_identifier) and has special rules. Specifically:

The blank identifier may be used like any other identifier in a declaration, but it does not introduce a binding and thus is not declared.

Also note that the section on Interfaces (https://golang.org/ref/spec#Interface_types) says:

each method must have a unique non-blank name

So that interface isn't even valid go; the fact that the compiler apparently accepts it is a bug. Whichever package is declaring it really shouldn't be doing that.

like image 50
Evan Avatar answered Oct 01 '22 08:10

Evan