Take the 2-minute tour ×

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?

share|improve this question
What do you mean by "enforce"? A value must implement an interface in order to be assigned to it, and this is enforced by the type checker. You don't have to declare that a type implements an interface, but this is by design and isn't an issue. –  SteveMcQwark Jun 15 '12 at 17:38
What are "C-style interfaces"? And what do you mean that Go doesn't "enforce" interfaces? The Go compilers certainly enforce that when you pass a type to a function that takes a certain interface, the interface is fulfilled, it does this statically at compile time, and is one of the things that makes Go great. –  uriel Jun 15 '12 at 18:38
add comment

2 Answers

up vote 7 down vote accepted

Yes. Go doesn't allow you to build type-hierarchies, so interfaces are very important to allow some polymorphism. Consider the sort.Interface defined in the package sort:

type Interface interface {
    // Len is the number of elements in the collection.
    Len() int
    // Less returns whether the element with index i should sort
    // before the element with index j.
    Less(i, j int) bool
    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)

The sort package contains a function sort(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:

type Sequence []int

// Methods required by sort.Interface.
func (s Sequence) Len() int {
    return len(s)
    return s[i] < s[j]
share|improve this answer
"you can even implement this interface on primitive types" You mean that you can define methods for custom types, which may be structurally equal to a primitive type. Sequence and []int are different types. –  newacct Jun 15 '12 at 20:12
Couldn't you just define those same methods on []int instead of Sequence and actually accomplish the OA's goal? Or can you not write new methods for the primitive types. –  matthias Jun 18 '12 at 3:42
mathias: Saw this randomly a year+ later, but no, can't define new methods on basic types. –  twotwotwo Nov 19 '13 at 18:58
add comment

I hope to know what a type check, both statical and at run time is, but I have no idea what is to "enforce an interface".

share|improve this answer
add comment

Your Answer


