Home > Backend Development > Golang > How Do I Modify Strings in Go, Knowing They Are Immutable?

How Do I Modify Strings in Go, Knowing They Are Immutable?

DDD
Release: 2024-10-26 04:33:02
Original
552 people have browsed it

How Do I Modify Strings in Go, Knowing They Are Immutable?

Altering Strings in Go: A Practical Solution

In Go, strings are immutable, meaning their contents cannot be modified once created. This can be frustrating when attempting to alter an existing string, but there is a simple solution using the fmt package.

Consider the following code:

<code class="go">package main

import "fmt"

func ToUpper(str string) string {
    new_str := 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 new_str
}

func main() {
    fmt.Println(ToUpper("cdsrgGDH7865fxgh"))
}</code>
Copy after login

This code attempts to uppercase lowercase characters in a string, but you will encounter an error: "cannot assign to new_str[i]". This is because strings are immutable.

To overcome this, we can convert the string to a slice of bytes and alter that instead:

<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

Here, []byte(str) creates a byte slice from the string, and string(new_str) converts the modified byte slice back to a string.

With this change, you can now alter strings and covert lowercase characters to uppercase:

fmt.Println(ToUpper("cdsrgGDH7865fxgh")) // Output: CDSRGgdh7865FXGH
Copy after login

The above is the detailed content of How Do I Modify Strings in Go, Knowing They Are 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