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

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

Linda Hamilton
Release: 2024-10-27 10:25:30
Original
905 people have browsed it

## 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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template