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

ぐ巨炮叔叔 提交于 2020-01-02 03:10:48

问题


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:


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



来源:https://stackoverflow.com/questions/14202181/what-is-this-variable-declaration-with-underscore-inline-interface-and-assignme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!