Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure a type implements an interface at compile time in Go

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.

like image 275
Matt Joiner Avatar asked May 08 '12 12:05

Matt Joiner


2 Answers

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.

like image 124
zzzz Avatar answered Oct 18 '22 04:10

zzzz


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?

like image 12
smile-on Avatar answered Oct 18 '22 04:10

smile-on