How to implement the _ () method?

I found an interface with a method called _ . I tried to implement it, but it does not work:

 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 _(int) method, but this also does not work:

 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 this could be a way to prevent the user from using an interface (like private interfaces in Java)?

+5
source share
1 answer

_ is an "empty identifier" ( https://golang.org/ref/spec#Blank_identifier ) and has special rules. In particular:

An empty identifier can be used like any other identifier in an ad, but it does not introduce a binding and therefore is not declared.

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

each method must have a unique non-empty name

So the interface is invalid; the fact that the compiler seems to recognize that this is a bug. Whatever package is announced, it really shouldn't be.

+5
source

Source: https://habr.com/ru/post/1200992/


All Articles