4 ms·
To answer your question, from the Go FAQ [0]: Why is len a function and not a method? We debated this issue but decided implementing len and frien
by shurcooL 10y ago
To answer your question, from the Go FAQ [0]:
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.
[0] https://golang.org/doc/faq#methods_on_basics https://golang.org/doc/faq#methods_on_basics
[1] https://golang.org/doc/go1compat https://golang.org/doc/go1compat
- frou_dh 10y agoIt's a bit of a mindfuck coming from mainstream OO languages that none of Go's built-in types have any methods† 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)
- kazinator 10y agoIf the object held in x is already mutable, why do we have to assign the returned value back to x also? 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.
- frou_dh 10y ago> 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)