7

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.

harm
  • 10,045
  • 10
  • 36
  • 41
  • It looks more like a static "structural type" check - e.g. it will fail to compile (fail early, fail fast) if an incompatible type is attempted to be assigned. I do not believe there is any "unpacking" occuring. (But I do not use Go.) –  Jan 07 '13 at 18:58
  • see https://stackoverflow.com/a/50414917/1153938 – Vorsprung Nov 05 '18 at 10:15

1 Answers1

12

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

zzzz
  • 87,403
  • 16
  • 175
  • 139