What does this snippet do when it indexes and tries to assign s[0]?
Predict what this program does. State exactly what each line produces — including whether it builds at all — and explain why.
s := "test"
fmt.Println(s[0])
s[0] = "R"
fmt.Println(s)
Then show how to change the first character if you needed to.
Diagnose the cause.
It does not compile. A Go string is an immutable, read-only sequence of bytes, so s[0] = ... is illegal. (s[0] reads a byte, not a string, so "R" is a type mismatch too.) To change a byte, convert: b := []byte(s); b[0] = 'R'; s = string(b).
- ✗Thinking a string can be mutated in place by assigning to an index like a slice
- ✗Believing
s[0]yields a one-character string rather than abytevalue - ✗Assuming the assignment compiles and fails (or no-ops) at runtime instead of being a build error
- →Why does
fmt.Println(s[0])print a number rather than the lettert? - →After
b := []byte(s), does mutatingbaffect the original strings?
What it prints
The program does not compile — it never runs.
A Go string is an immutable, read-only sequence of bytes. The string header points at a byte array you may not modify, so s[0] = "R" is the compile error "cannot assign to s[0]". On top of that, the expression s[0] has type byte (i.e. uint8), while "R" is a string, so the assignment would fail the type check regardless.
Had it built, fmt.Println(s[0]) would print 116 — the decimal ASCII code of the byte t, not the letter itself, because indexing a string yields a byte and Println prints its numeric value.
How to change a character
Convert to []byte, modify, convert back:
s := "test"
b := []byte(s) // a copy of the bytes — a separate array
b[0] = 'R' // 'R' is a rune/byte literal, not a string
s = string(b) // s == "Rest"
[]byte(s) makes a copy of the bytes, so the original string is left unchanged — its immutability is what lets string values be safely shared and used as map keys. For non-ASCII characters, work via []rune so you don't slice a multi-byte UTF-8 sequence.