How do we tell the compiler that our type implements the interface?

At the interview, I was asked such a question that put me into a stupor. As I understand tech guy wanted to know if I understand what the concept of interfaces in Go is based on. So after some research didn’t find the answer. Any idea how to answer this question?

type name interface {} is not a valid answer

The compiler will consider a given type beeing of a given interface, if and only if all methods of that interface are implemented.

There is no need to tell the compiler that this struct shall be of interface Foo.

To make sure that your struct matches a given interface at compile time use this snippet:

// for pointers to struct
type MyType struct{}
var _ MyInterface = (*MyType)(nil)

// for struct literals
var _ MyInterface = MyType{}

See https://medium.com/@matryer/golang-tip-compile-time-checks-to-ensure-your-type-satisfies-an-interface-c167afed3aae

1 Like

short answer:

We don’t

i.e. the compiler figures it out for itself.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.