2

In Python, lists offer an append() method which can be called using standard Python method syntax; for example:

>>> my_list = []
>>> my_list.append('a', 'b', 'c')
>>> my_list
['a', 'b', 'c']

This syntax is intuitive to me, and this pattern is common in list implementations across many OO languages.

Lately, I've been working more closely with Go, and I'm trying to get a better understanding of some of the design choices made in the language. Most notably, why is append() defined as a regular function (taking the slice to append to as the first argument, and returning the newly-constructed slice), rather than a method on the slice type?

I'm aware that Go doesn't have a self/this construct, but the standard library takes some liberties with how its functions are defined with respect to the rest of the language; for example, make() takes a type as a first argument, and this is, as far as I know, not possible when defining a new function.

Is it just a nod to C's pattern of passing references to variables, rather than returning new variables?

  • 1
    I have to ask: does it really matter, other than as a personal preference? – Robert Harvey Feb 18 '16 at 6:16
  • 4
    @RobertHarvey since you mention it, yeah, it's a big factor. But I'm hoping this question will be relevant to more people interested in language design choices rather than just myself. If you or other community members find the question subjective or off-topic, I'll delete it, though. – Jules Feb 18 '16 at 15:59
  • I think this is more important from the compiler design side of things. – Joe Oct 5 '16 at 14:44
4

The Go FAQ has a related question:

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.

len would seem to be in the same boat as append. If they were methods, they should affect whether or not the builtin types fit various interfaces. This made adding them as methods somewhat more complicated then just having special builtins for them. They decided it didn't matter in practice, so the extra complexity wasn't worth it.

|improve this answer|||||
  • Don’t have rep to make a tiny edit but: then -> than – Wildcard Feb 13 '19 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.