Immutable strings

Why doesn’t this code compile?

s := "hello"
s[0] = 'H'
../main.go:3:7: cannot assign to s[0]


Go strings are immutable and behave like read-only byte slices (with a few extra properties).

To update the data, use a rune slice instead.

buf := []rune("hello")
buf[0] = 'H'
s := string(buf)
fmt.Println(s)  // "Hello"

If the string only contains ASCII characters, you could also use a byte slice.

See String functions cheat sheet for an overview of strings in Go.

Share this page: