Interfaces are implemented implicitly

A type implements an interface by implementing its methods. There is no explicit declaration of intent, no "implements" keyword.

Implicit interfaces decouple the definition of an interface from its implementation, which could then appear in any package without prearrangement.

interfaces-are-satisfied-implicitly.go

  1. package main
  2. import "fmt"
  3. type I interface {
  4. M()
  5. }
  6. type T struct {
  7. S string
  8. }
  9. // This method means type T implements the interface I,
  10. // but we don't need to explicitly declare that it does so.
  11. func (t T) M() {
  12. fmt.Println(t.S)
  13. }
  14. func main() {
  15. var i I = T{"hello"}
  16. i.M()
  17. }