Welcome,
In this article we're going to discuss all there is to know about arrays and slices in Go, we'll go deep talking about their internal st...
For further actions, you may consider blocking this person and/or reporting abuse
Great in depth discussion on a less understood aspect of Go. Thanks!
Thank you so much for your kind words
very helpful
Re "Potential Quirks of Slices", I think you may be wrong about
regexp.Find
holding onto memory the way you describe. This used to be a problem, and if you read an earlier Go blog post about slices, you may think it still is a problem. But it hasn't been a problem for a while.The old version of
regexp.Find
looked like this (note the last line especially):The new version looks like this (again, the last line is key):
Because the new version uses a full slice expression, I don't think that it holds onto memory any longer. The third item in a full slice expression specifies the maximum capacity of the slice. The definition states that the capacity of the resulting slice is no greater (in this case) than
a[1] - a[0]
. That means that the capacity will be no longer than the length of the string found, in your casegopher
.Full slice expressions were introduced in December of 2013, and
regexp.Find
was fixed sometime after that. This is great to know about because we can also use full slice expressions to control how much of a backing array is exposed by a slice. This can protect us from blocking the garbage collector, as here, and it can also prevent the caller from being able to (accidentally or intentionally) changing parts of the backing array that they shouldn't have access to. (That is, in the old version ofregexp.Find
, the calling code would have access to a lot more of the 1 GB document in your example than just the word "gopher." In the new version, that's protected against.)I did not know that
Thanks for the correction!
I did not quite understand this.
Even full slicing doesnt do a deep copy. It still exposes the same underlying array.
For instance, int the following program , editing s would also edit the b1 slice.
I am using go 1.23 version.
Error on line 14 of codeblock 11
Should read
Thanks for catching that.
Hi! Nice article. Just a comment: "len is a built-in function that returns the number of items in an array of slice" shouldn't be "in an array or slice"?
Uh oh... this part might need revising:
Hi, the result is 3,4
cap(subSlice) = 4
i my case fmt.Println(len(subSlice), cap(subSlice)), gives 3 5. Looks like the subSlice is retaining the slice length, when we ommit it during creation
very helpful. Thanks!