Go: Adding a 'caution' about copying slice using brackets to Slices concept text

This is minor, but also easy to do :slight_smile:

In the Slices concept section, I propose including a ‘caution’ block right after the part that illustrates how to create new slices from existing ones using square-bracket notation. The caution should be (or similar to) as follows:

Be aware that although newSlice is a different slice than withData , they both point to the same underlying array. Consequently, modifications to elements in withData will also affect newSlice :

withData := []int{0,1 ,2 ,3 ,4, 5} 
newSlice := withData[:]
withData[0] = 9
fmt.Println(newSlice[0]) //Prints 9

This is a common pitfall for those just getting started with Go’s slices. Since we don’t go in-depth on this topic in this concept, I think it’s definitely worth noting.

I was going to submit a PR for this, but I’ve just gotten back from a 2 year-ish hiatus and noticed that the track is closed for contributions now (read the blog post, fully understand :slight_smile:). Anyway hope that makes sense.

“Unfortunately”, there would be even more to mention. The memory of the old and new array is only shared, as long as the capacity is huge enough when appending new elements. Or they will have different memory.

Furthermore, slices work more like pointers when used as function parameters. So you can change its values within the calling function.

Wondering if this could be overwhelming when just starting with slices. I had several mentoring sessions where we could talk 1:1 about those specialities. And usually there was more to talk about.

Agreed. I intentionally left out the part about when they seize to share the same underlying array which one of the reasons why I elected to suggest adding a caution relevant to only the “copy by brackets” section.

I suppose it’s intentional to leave some of this stuff out for something like concept articles to avoid overwhelming new language learners, but I do believe those are common enough ways to “copy” slices (whether by a simple assignment, or using the square bracket notation), especially for learners coming from other languages that would warrant pointing out this behaviour.

From my personal experience, I think a very good approach to understanding Slices is to get learners to start with pure Go Arrays first, but I will leave that discussion to another thread.