r/programming_funny • • Sep 12 '21

Stuff about interfaces

I wrote this when I was trying to understand them, if it's any use to anyone.

---

Go has no classes. Go has interfaces. For example, this is an interface from the "sort" package, boringly called Interface.

type Interface interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

The sort package provides a bunch of built-in functions such as Sort and IsSorted and Reverse which will work with any type that implements methods with the names and signatures in the interface. So for example I can define these methods for a list (a "slice" in Go) of things of the RGBA type in the color package (ordering colors by redness, just for example):

type colors []color.RGBA

func (k colors) Less(i, j  int) bool {
    return k[i].R < k[j].R
}

func (k colors) Swap(i, j int) {
    k[i], k[j] = k[j], k[i]
}

func (k colors) Len() int {
    return len(k)
}

And now I can apply all the functions in the sort package to a thing of type colors.

Also, I can define my own functions on the interface, and they can be applied to anything that implements its methods. This is "static duck typing". For example, here's a function to measure the unsortedness:

func Unsortedness(L sort.Interface) float64 {
    count := 0;
    for i := 0; i  < L.Len(); i++ {
	for j := i + 1; j < L.Len(); j++ {
		if L.Less(j,i) {count++}
	}
    }
    return float64(count) / (float64(L.Len()\*L.Len()-L.Len()) / 2.0)
}

And here's a function that executes a shuffle:

func KFYShuffle(L sort.Interface) {
    for i := 0; i < L.Len(); i++ {
	L.Swap(i, i + rand.Intn(L.Len()-i));
    }
}
2 Upvotes

5 comments sorted by

View all comments

Show parent comment

1

u/bkatrenko Sep 14 '21

interfaces are not really "alternative to classes" :) But yes, if we bind functions for some struct, its possible to build smth in OOP style.

>then not only can you test them independently of it, you can also test it independently of them. Yes? -> Yes :)

1

u/Inconstant_Moo Sep 15 '21 edited Sep 15 '21

Well I mean that classes allow you to treat different things as the same kind of thing by inheritance, and interfaces let you do it by method signatures. They're both a way of defining a group of types. But since the method signatures are the important thing, why bother with classes?