4 ms·
The 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 o
by Laremere 12y ago
The 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.