如何实现 _() 方法?

huangapple go评论68阅读模式
英文:

How to implement _() method?

问题

我发现一个接口中有一个名为_的方法。我尝试实现它,但是它不起作用:

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 }

运行代码后报错:

./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 }

运行代码后报错:

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

为什么会这样?_方法的目的是什么?我认为它可能是一种防止人们实现接口的方式(类似于Java中的私有接口)?

英文:

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

答案1

得分: 5

_ 是“空白标识符”(https://golang.org/ref/spec#Blank_identifier),具有特殊规则。具体来说:

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

还要注意接口部分(https://golang.org/ref/spec#Interface_types)中的说明:

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

所以该接口甚至不是有效的Go代码;编译器似乎接受它是一个错误。声明该接口的包不应该这样做。

英文:

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

huangapple
  • 本文由 发表于 2014年8月24日 05:02:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/25466356.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定