I understand that Go string is basically an array of byte. What is the explanation why str[0] = str[1] is not allowed? Thanks!
str := "hello"
str[0] = str[1]
// expecting eello
I understand that Go string is basically an array of byte. What is the explanation why str[0] = str[1] is not allowed? Thanks!
str := "hello"
str[0] = str[1]
// expecting eello
I understand that Go string is basically an array of bytes.
Not exactly. A string is made up of
If you could update individual runes of a given string variable, then strings would be mutable, against the wishes of the Go designers:
Strings are immutable: once created, it is impossible to change the contents of a string.
See also this post on the golang.org blog:
In Go, a string is in effect a read-only slice of bytes.
Immutability has many advantages—for one thing, it's easy to reason about—but it can be perceived as a nuisance. Of course, overwriting a string variable is legal:
str := "hello"
str = "eello"
Moreover, you can always convert the string to a data structure that is mutable (i.e. a []byte
or a []rune
), make the required changes, and then convert the result back to a string.
str := "hello"
fmt.Println(str)
bs := []byte(str)
bs[0] = bs[1]
str = string(bs)
fmt.Println(str)
Output:
hello
eello
However, be aware that doing so involves copying, which can hurt performance if the string is long and/or if it's done repeatedly.
Go strings are immutable and behave like read-only byte slices,To update the data, use a rune slice instead;
package main
import (
"fmt"
)
func main() {
str := "hello"
fmt.Println(str)
buf := []rune(str)
buf[0] = buf[1]
s := string(buf)
fmt.Println(s)
}
Output:
hello
eello