Home  >  Article  >  Backend Development  >  ## Why Can\'t I Modify a String in Place in Go?

## Why Can\'t I Modify a String in Place in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 10:25:30815browse

## Why Can't I Modify a String in Place in Go?

Why can't I modify a string in place in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn