-3

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
jub0bs
  • 60,866
  • 25
  • 183
  • 186
Leo
  • 5
  • 2
  • 6
    [Why are strings immutable in many programming languages?](https://stackoverflow.com/q/9544182/995714), [Which types are mutable and immutable in the Google Go Language?](https://stackoverflow.com/q/8018081/995714) – phuclv Sep 09 '21 at 05:41
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 16 '21 at 06:27

2 Answers2

3

I understand that Go string is basically an array of bytes.

Not exactly. A string is made up of

  • a pointer to an array of bytes, and
  • an integer that corresponds to the length of that array.

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

(Playground)

However, be aware that doing so involves copying, which can hurt performance if the string is long and/or if it's done repeatedly.

jub0bs
  • 60,866
  • 25
  • 183
  • 186
0

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   
Gopher
  • 721
  • 3
  • 8