Home >Backend Development >Golang >## How Can I Convert Lowercase Characters to Uppercase in a Go String?
Q: I want to convert lowercase characters to uppercase in a string, but Go throws an error: "cannot assign to new_str[i]". How can I achieve this?
In Go, strings are immutable, meaning once created, their contents cannot be modified. This behavior aligns with the Go Language Specification, which states:
"Strings are immutable: once created, it is impossible to change the contents of a string."
To modify a string in Go, you have two options:
Here is a modified version of your code that uses a []byte slice to alter the characters.
<code class="go">package main import ( "bytes" "fmt" ) func ToUpper(str string) string { strBytes := []byte(str) for i := 0; i < len(str); i++ { if str[i] >= 'a' && str[i] <= 'z' { chr := uint8(rune(str[i]) - 'a' + 'A') strBytes[i] = chr } } return string(strBytes) } func main() { fmt.Println(ToUpper("cdsrgGDH7865fxgh")) } </code>
The above is the detailed content of ## How Can I Convert Lowercase Characters to Uppercase in a Go String?. For more information, please follow other related articles on the PHP Chinese website!