doucang2871 2015-10-12 20:19
浏览 47
已采纳

如何将golang结构标记为实现接口?

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条回答 默认 最新

  • dongtuo1482 2015-10-12 20:20
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?