Your solution certainly works - but because you allocate a smaller slice than you need in the end, it is going to allocate and copy *again* as soon as you hit your second append.
You could instead use the other form of make (three parameter) to create an *empty* slice with the full length needed pre-allocated, then append thrice to get your desired result. func make([]T, len, cap) []T If you also use a simple helper function, you can make the result (in my opinion, anyway), much more readable. It does carry a performance penalty, though, as it involves iterating a loop. Whether that's worth it depends on how much speed matters over readability and maintainability. https://play.golang.org/p/-KOVGMP8KB Howard On Sunday, November 20, 2016 at 12:14:31 PM UTC-6, Bogdan Katyński wrote: > > Thank you very much for the replies. > I've read the blog about slices again and I'm pretty sure I know what is > happening in my example and how are dst and src interconnected. > > I've started thinking how I can achieve what I'm looking for in the nicest > way, and after some trial and error, I've come up with this solution: > https://play.golang.org/p/F3GWDKCrLo > > Not sure if it's the nicest way but it was the smallest change and works. > > Thanks again for the answers and inspiring me to dig deeper :) > Bogdan > > > > W dniu niedziela, 20 listopada 2016 09:52:59 UTC użytkownik Val napisał: >> >> Hello Bogdan >> You're asking a very legit question. Slices are powerful but using >> combinations of append and reslicing can be surprisingly subtle. >> >> Step1 is easy: slicing is basically creating a new header referencing a >> position in an existing array, it does NOT by itself modify src. >> >> Step3 is more difficult: dst and src don't share any overlapping memory >> location anymore, though they did in Step1 and Step2. This is what happens >> when appending elements beyond capacity (beyond last slot of underlying >> array): then a fresh new array is allocated and returned, now independent >> from src. To understand why there is an overflow at all (even if dst has no >> more than 8 items), you must consider that after Step1, the fist slot of >> dst is the seond slot of the underlying array. >> >> Hope this helps. >> Same sort of puzzle here: https://go-traps.appspot.com/#append >> >> -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.