The Go language has interface types as features, analogous to C-style interfaces. Go’s interface types, though, don’t seem to be enforced — they merely define protocol without actually being applied to a type. As they are not enforced, is it still a good idea to use interfaces?
The Go language has interface types as features, analogous to C-style interfaces. Go’s interface
Share
Yes. Go doesn’t allow you to build type-hierarchies, so interfaces are very important to allow some polymorphism. Consider the
sort.Interfacedefined in the packagesort:The
sortpackage contains a functionsort(data Interface)that expects any object that implements this interface. Without interfaces, such form of polymorphism would not be possible in go. The fact that you don’t have to explicitly annotate that your type implements this interface, is irrelevant.The cool part about go is that you can even implement this interface on primitive types, as long as the type is defined in the same package. So the following code defines a sortable array of integers: