-1

The following is a standard code to check at compile time if struct A implements interface fooer

var _ myInterface = (*myStruct)(nil)

It is for example presented here.

I am a little confused of cases when A and when *A implements a given interface. I think the above code fails to differentiate between those two cases. This may cause some hard-to-find bugs (e.g. json.Marshaler interface)

package main

type fooer interface{ foo() }

type A struct{}
type B struct{}

func (*A) foo() {}
func (B) foo()  {}

var _ fooer = (*A)(nil)
var _ fooer = *(*A)(nil) // fails to compile
var _ fooer = A{}  // fails to compile
var _ fooer = &A{}

var _ fooer = (*B)(nil)
var _ fooer = *(*B)(nil)
var _ fooer = B{}
var _ fooer = &B{}

func main() {}

Sadly maybe, I did not manage to make compilation fails for struct B, where foo is defined on non-pointer receiver. Is it an issue in practice? Is there a way to test that? Would it be better practice to use var _ myInterface = myStruct{} to test if a type implements an interface?

Remi.b
  • 16,247
  • 25
  • 74
  • 153
  • 2
    Both `B` and `*B` implement `fooer`. Methods with non-pointer receiver are in the method set of both types. You should test the type you want to implement the interface. If you want `B` to implement it, test for `B{}`. If you want `*B` to implement it, test for `(*B)(nil)`. – icza May 31 '22 at 09:01
  • 1
    "Sadly maybe, I did not manage to make compilation fails for struct B, where foo is defined on non-pointer receiver." Because that is the correct behaviour. "Is it an issue in practice?" No. "Is there a way to test that?" Test what? "Would it be better practice to use var _ myInterface = myStruct{} to test if a type implements an interface?" There is no "better". The later is more readable IMHO. – Volker May 31 '22 at 09:03
  • 1
    implementation of interfaces via value or pointer has been covered multiple times already, anyway please note that framing questions as [asking for "best practices" is almost always off-topic](https://meta.stackoverflow.com/questions/337031/primarily-opinion-based-on-best-practice-questions) – blackgreen May 31 '22 at 09:12
  • Thanks everyone. @icza you answered my question. Do you want to make an answer out of your comment or would you advice me to just delete my post given the negative reception? – Remi.b May 31 '22 at 09:35
  • 1
    @Remi.b The question is already closed. Delete it if you want to. – icza May 31 '22 at 09:57

0 Answers0