How Can I Modify a String in Go If It\'s Immutable?

DDD
Release: 2024-10-26 12:38:29
Original
943 people have browsed it

How Can I Modify a String in Go If It's Immutable?

String Alteration in Go: Resolving the "Cannot Assign to String" Error

Go strings are immutable, meaning they cannot be directly modified once created. This limitation often raises the error "cannot assign to new_str[i]" when attempting to alter a string's contents. To overcome this challenge and modify strings, an alternative approach is required.

One solution is to convert the string to a byte slice, which can be altered like an array. This technique allows for the replacement of characters within the string. The following code demonstrates this approach:

<code class="go">func ToUpper(str string) string {
    new_str := []byte(str)
    for i := 0; i < len(str); i++ {
        if str[i] >= 'a' && str[i] <= 'z' {
            chr := uint8(rune(str[i]) - 'a' + 'A')
            new_str[i] = chr
        }
    }
    return string(new_str)
}</code>
Copy after login

In this code, the string str is converted to a byte slice new_str. The byte slice is then iterated over, comparing each byte to the ASCII lowercase character range. If a lowercase byte is encountered, it is replaced with its uppercase ASCII equivalent. Finally, the modified byte slice is converted back to a string and returned.

This approach enables the alteration of strings in Go while maintaining their immutability. It provides a flexible and efficient way to manipulate strings in various contexts.

The above is the detailed content of How Can I Modify a String in Go If It\'s Immutable?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!