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
NobbZ
(Norbert Melzer)
March 11, 2021, 10:53am
2
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
.
j-forster
(Johann Forster)
March 11, 2021, 7:49pm
3
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
amnon
(amnon bc)
March 14, 2021, 6:47pm
4
short answer:
We don’t
i.e. the compiler figures it out for itself.
system
(system)
Closed
June 12, 2021, 6:47pm
5
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.