4 ms·
I'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
by alecbenzer 12y ago
I'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.