如何实现_()方法?

时间:2014-08-23 21:02:01

标签: types interface go overloading

我在其中找到了一个名为_的方法的接口。我尝试实现它,但它没有工作:

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)

我还尝试添加重载方法_(int),但这样做不起作用:

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

为什么呢?这个_方法的目的是什么?我认为它可能是一种阻止人们实现接口的方法(比如Java中的私有接口)?

1 个答案:

答案 0 :(得分:5)

_是"空白标识符" (https://golang.org/ref/spec#Blank_identifier)并有特殊规则。具体做法是:

  

空白标识符可以像声明中的任何其他标识符一样使用,但它不会引入绑定,因此不会声明。

另请注意,接口(https://golang.org/ref/spec#Interface_types)部分说:

  

每个方法必须具有唯一的非空白名称

所以界面甚至没有效果去;编译器显然接受它的事实是一个错误。无论哪个包宣布它都不应该这样做。

相关问题