这是使用下划线、内联接口和赋值的变量声明是什么意思?

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

What is this variable declaration with underscore, inline interface and assignment?

问题

这段Go代码做了什么?

var _ interface {
	add(string) error
} = &watcher{}

我相信&watcher{}返回了两个东西,第一个被丢弃了,第二个被赋值给...一个接口?我在Github上的fswatch代码中找到了这段代码。

英文:

What does this snippet of Go code do?

var _ interface {
	add(string) error
} = &watcher{}

I believe &watcher{} returns two things, the first is discarded and the second is assigned to ... an interface? I found the code in fswatch on Github.

答案1

得分: 12

这个结构将声明一个具有空白标识符名称的变量,其类型由类型字面量给出;在这种情况下是一个接口定义。接下来是一个初始化表达式 - 在这种情况下是一个复合字面量的指针。

代码片段的整体功能是静态地确保*watcher满足所述的接口,因为_变量在任何方式下都不会被实例化,只能观察到初始化器的任何可能的副作用。可以是静态的(如本例)或动态的(例如调用一个在运行时分配给某些全局变量、注册处理程序等的函数)。

英文:

This construct will declare a variable with an blank identifier name with type given by a type literal; an interface definition in this case. What follows is in initializer expression - a pointer to a composite literal in this case.

Overall functionality of the snippet is to statically ensure that a *watcher satisfies the said interface as the _ variable is not materialized in any way and only any possible side effects of the initializer can be observed. Either static (as in this case) or dynamic (like e.g. calling a function which assigns at runtime to, say, some global vars, registers a handler, etc.)

huangapple
  • 本文由 发表于 2013年1月8日 02:51:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/14202181.html
匿名

发表评论

匿名网友

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

确定