Search code examples
gointerface

Why does os.Signal interface include an apparently useless method?


I came across this declaration in "os/signal" package:

type Signal interface {
    String() string
    Signal() // to distinguish from other Stringers
}

What potential problem(s) are being solved by adding what seems to be a useless method "to distinguish from other Stringers"?


Solution

  • What types can you pass to signal.Ignore(sig os.Signal)? If os.Signal is interface { String() string } then it would appear that it's anything with a String() string method, which is wrong. Adding the "useless" Signal() to the interface, the set of types that can be used is narrowed.

    For example, if you use gopls to find types that implement the interface, the addition of the "useless" method will cause it to find the right types with typically no false positives.

    This mechanism of adding a dummy method to constrain types is not perfect, but it's a reasonable pragmatic choice.