30

I have interface:

  type MyInterface interface {
  ...
  }

and I want to mark that my struct implements it. I think it is not possible in go, but I want to be certain.

I did the following, but I think it results in an anonymous variable that implements interface. Am I right?

  type MyStruct struct {
    ...
    MyInterface
  }
Sergei G
  • 1,561
  • 3
  • 18
  • 26
  • 10
    Go FAQ: [Why doesn't Go have "implements" declarations?](https://golang.org/doc/faq#implements_interface) and answer [How can I guarantee my type satisfies an interface?](https://golang.org/doc/faq#guarantee_satisfies_interface) – icza Oct 12 '15 at 20:24
  • Does this answer your question? [Ensure a type implements an interface at compile time in Go](https://stackoverflow.com/a/60663003) –  Mar 13 '20 at 03:37
  • Does this answer your question? [Go - how to explicitly state that a structure is implementing an interface?](https://stackoverflow.com/questions/31753282/go-how-to-explicitly-state-that-a-structure-is-implementing-an-interface) – SOFe Aug 01 '23 at 10:31

1 Answers1

68

In Go, implementing an interface is implicit. There is no need to explicitly mark it as implementing the interface. Though it's a bit different, you can use assignment to test if a type implements an interface and it will produce a compile time error if it does not. It looks like this (example from Go's FAQ page);

type T struct{}
var _ I = T{}       // Verify that T implements I.
var _ I = (*T)(nil) // Verify that *T implements I.

To answer your second question, yes that is saying your struct is composed of a type which implements that interface.

Will C
  • 1,750
  • 10
  • 20
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115