简体   繁体   中英

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

_ 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM