Why doesn’t this code compile?
s := "hello" s = 'H' fmt.Println(s)
../main.go:3:7: cannot assign to s
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 = '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: