Strings in Go are immutable, meaning that once created, you cannot modify their contents. This is evident from the following error: "cannot assign to new_str[i]".
To change the contents of a string, you must first cast it to a []byte slice. Unlike strings, byte slices are indeed mutable. You can then perform your desired modifications on the byte slice and cast it back to a string using the string(...) function.
Here's a modified version of your code that uses byte slices to change lowercase characters to uppercase:
<code class="go">func ToUpper(str string) string { bytes := []byte(str) for i := 0; i < len(str); i++ { if bytes[i] >= 'a' && bytes[i] <= 'z' { chr := uint8(rune(bytes[i]) - 'a' + 'A') bytes[i] = chr } } return string(bytes) }</code>
Now, when you call ToUpper("cdsrgGDH7865fxgh"), it will correctly convert all lowercase characters to uppercase.
The above is the detailed content of ## Why Can\'t I Modify a String in Place in Go?. For more information, please follow other related articles on the PHP Chinese website!