what does it mean when we say Go’s interface is implicitly satisfied?

tags: learning go programming

content

We always say in Go, an interface is satisfied implicitly, what does that mean?

  • look at a C# code first:
// Interface
interface IAnimal 
{
  void animalSound(); // interface method (does not have a body)
}
 
// Pig "implements" the IAnimal interface
class Pig : IAnimal 
{
  public void animalSound() 
  {
    // The body of animalSound() is provided here
    Console.WriteLine("The pig says: wee wee");
  }
}
  • In Go, an interface is satisfied implicitly
    • this statement is mainly talking about the programming language’s syntax
    • in Java and C#, you need explicit keywords like class MyClass : MyInterface

my question:

type MyInterface interface {
	MyFunc() 
}
func (s MyStruct) MyFunc() {}
 
// call MyFunc on MyStruct:
s := MyStruct{}
s.MyFunc()
  • in Go, we have the above code, doesn’t that mean we are explicitly saying that MyStruct implements MyFunc?

    • writing the function receiver does NOT declare “MyStruct implements MyInterface
    • instead, the function declaration only means: MyStruct has method MyFunc
    • in the above example, MyInterface isn’t even being used!!!!
  • extending from the above code:

func DoSomething(i MyInterface){ fmt.Println("do something") }
DoSomething(s)
  • we DO NOT have statements like “MyStruct implements MyInterface” anywhere in the code
  • But we can pass s MySruct into DoSomething, which expects type MyInterface
  • this means MyStruct satisfies MyInterface explicitly, by having all methods in MyInterface
    • if we change MyInterface to type MyInterface interface { MyFunc(), MyFunc2()}, we will not be able to put MyStruct in DoSomething

up

down

reference