英文:
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.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论