How can I ensure that a type implements an interface at compile time? The typical way to do this is by failure to assign to support interfaces from that type, however I have several types that are only converted dynamically. At runtime this generates very gruff error messages, without the better diagnostics given for compile time errors. It's also very inconvenient to find at run time that types I expected to support interfaces, do in fact not.
Assuming the question is about Go, e.g.
var _ foo.RequiredInterface = myType{} // or &myType{} or [&]myType if scalar
as a TLD will check that for you at compile time.
In the Go language there is no "implements" declaration by design. The only way to ask the compiler to check that the type T
implements the interface I
by attempting an assignment (yes, a dummy one). Note, Go lang differentiates methods declared on structure and pointer, use the right one in the assignment check!
type T struct{}
var _ I = T{} // Verify that T implements I.
var _ I = (*T)(nil) // Verify that *T implements I.
Read FAQ for details Why doesn't Go have "implements" declarations?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With