Why is len a function and not a method?
We debated this issue but decided implementing len and friends as functions was
fine in practice and didn't complicate questions about the interface (in the Go
type sense) of basic types.
Also worth noting is that debate happened in 2009 or earlier, which is 7 years ago. After that, Go 1 has been released with its promise/guarantee of compatibility [1], so changing the language is not possible. It is what is, and significant language changes can only happen in Go 2. Until then, many, many people and companies are using Go 1 with huge success and happiness and have built great things with it. In practice, I find it works really well.I guess there's a certain cleanliness whereby all methods exist on one side of the language/library dividing line.
† The sole exception perhaps being "error", which is a pre-declared interface comprising 1 method.
---
In a similar vein, this takes some getting used to:
x.append(y) # No!
append(x, y) # Probably Not!
x = append(x, y) # Yes! (but this is not Lisp - despite appearances, the collection is mutable)Ah! Beacause it is like Lisp?
(setf x (nconc x y))
I.e. the empty list cannot be mutated to non-empty, but non-empty can mutate to different non-empty.Surely, we could wrap append with a appendf (append functional), such that we can do:
x = appendf(x, y); # no mutation: original x preserved
Inside appendf we might have to do something gross, like duplicate the entire object, and append to the copy.That's why you have to care about the return value in normal Go. The slice x opaquely references a backing array with a certain max capacity. If you append one too many times then it's going to return a completely new value that references a new backing array that has more legroom ... with all your existing elements copied into it.
(p.s. I just noticed that Go actually considers that "Probably Not" case a compile-time error)
Why generic builtins instead of a Channel interface?