Today I learnt about the practice of statically asserting that a type in Go implements an interface. This is for cases where you want to guarantee a given type implements an interface, but you’re not in a position to assert this yourself within your own code.
An example of this might be to demonstrate a given type implements json.Marshaller. You’re generally not going to assert this yourself using a type assertion, as it will only be useful to the JSON marshalling logic. Yet you may want to demonstrate that the type does implement this interface, or rely on the type checker to verify this.
The approach you will take to do this is as follows:
var _ json.Unmarshaller = (*MyType)(nil)The attempt to assign a *MyType value to a json.Unmarshaller variable will error out if *MyType doesn’t implement json.Unmarshaller. This forces the maintainer of MyType to implement this interface, without synthetically adding type assertions within dummy functions, for example.
Apparently, this is a technique documented in the official documentation, amongst other places. The docs does make the point of not doing this for every type, particularly if you’re already asserting whether types implement interfaces in regular code. And I’m not sure how I feel about this practice in general. My understanding of the role of interfaces in Go is to support abstractions that are “discovered” over time, and that being too early in imposing interfaces over types — something this construct supports — is considered a bit of an anti-pattern. But I guess it could still be useful in some circumstances.