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
MyStructimplementsMyFunc?- writing the function receiver does NOT declare “
MyStructimplementsMyInterface” - instead, the function declaration only means: “
MyStructhas methodMyFunc” - in the above example,
MyInterfaceisn’t even being used!!!!
- writing the function receiver does NOT declare “
-
extending from the above code:
func DoSomething(i MyInterface){ fmt.Println("do something") }
DoSomething(s)- we DO NOT have statements like “
MyStructimplementsMyInterface” anywhere in the code - But we can pass
s MySructintoDoSomething, which expectstype MyInterface - this means
MyStructsatisfiesMyInterfaceexplicitly, by having all methods inMyInterface- if we change
MyInterfacetotype MyInterface interface { MyFunc(), MyFunc2()}, we will not be able to putMyStructinDoSomething
- if we change