5 ms·
What happens when you write var x []string = strs ? If you make a copy of the slice's underlying array and point x to the copy, then you are hiding a potent
by tjgq 12y ago
What happens when you write
var x []string = strs ?
If you make a copy of the slice's underlying array and point x to the copy, then you are hiding a potentially expensive allocation behind an apparently innocuous initialization (something that Go tries very hard not to do).
If, instead, you make x point to the same underlying array as strs, then you would have to have immutable slices, which is something that currently does not exist in Go.
I'm not saying neither of the two options is acceptable, but they surely raise issues that go against the grain of the language.
- alecbenzer 12y agoI'd expect it to do the exact same thing as var x []string = []string{"Hello", "world!"} which I guess does a "copy" of the temporary? (Or at least requires O(slice's size) work). But so const s string = "Hello, world!" var x string = s Doesn't do a copy of the data? That's somewhat satisfying of an explanation, though I guess I still don't see the huge trouble in having it do the copy for a slice. (I mean, really, how large is a slice embedded into the source code going to be?)
- Laremere 12y agoThe second example doesn't do a copy of the data. The underlying data storage of a string is immutable. In your example x would point to the memory location of the constant string s. If you do for example: x += "\n" Then new memory would be allocated, and the current contents of x would be copied in, and the "\n" would be copied in after it. Since the string's type can't modify the underlying data, it's safe. However a slice has the ability to do so, the data must be copied. As the article link elaborates on, one of the main design features of constants in Go is their ambiguous type. Since slices or arrays require their components to have a specific type, the only remaining feature is that they do the copy as you talk about. (Unless you want to really complicate slice logic.) It's a rare request that you're talking about. If you have a slice which code references but doesn't edit, make it a package level var and be done with it. If you need to be able to get the same starting slice which you can then edit, make a function to return and initialize it. These solutions fit well within the language's design, and mean that everyone learning the language doesn't have to learn a specific feature that they could easily do without.