35

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
  }
1

1 Answer 1

76

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, that has been one of the best tips I have kept in my GO lang toolbox for years.
hi this may be an thread but, how do you implement design patterns if implementation will be like that? is it still possible>
This was very helpful. Thanks a lot for this technique to check what methods are missing.
While the technique is neat (thanks for sharing), but if T needs to implement an interface I, wouldn't compiler fail later anyway, because some method is going to be missing in T. Of course, I can see this being very handy when scaffolding code to fill in details later, or by someone else.
Yes, the compilation would fail later if you use it in your code. One place I would think this would be particularly useful is if you are creating a library. You could create a struct, and you want to make sure the struct can be marshaled to JSON, but you never actually do the marshaling yourself. Another use case may be if you are refactoring, you want to get a warning as soon as possible if you ever change the struct so that it no longer satisfies the interface.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.