Hacker News new | past | comments | ask | show | jobs | submit login

If 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.



> 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)




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: