Strings are Immutable in Go: Explanation and Examples
In Go,
strings are immutable, meaning once created, their content cannot be changed. To modify a string, you must create a new string from parts or convert it to a mutable type like a []byte.Syntax
A string in Go is a sequence of bytes enclosed in double quotes. You declare a string like this:
var s string = "hello"Here, s holds the string value. Since strings are immutable, you cannot change any character inside s directly.
go
var s string = "hello" // s[0] = 'H' // This will cause a compile error because strings are immutable
Example
This example shows how to create a new string by modifying an existing one using a byte slice, since strings themselves cannot be changed.
go
package main import "fmt" func main() { s := "hello" // Convert string to byte slice to modify b := []byte(s) b[0] = 'H' // Convert back to string s2 := string(b) fmt.Println(s) // original string fmt.Println(s2) // modified string }
Output
hello
Hello
Common Pitfalls
Trying to change a string character directly causes a compile-time error because strings are immutable. Instead, convert the string to a []byte or []rune, modify it, then convert back to a string.
Also, remember that converting to []byte works well for ASCII but may break multi-byte characters like emojis. Use []rune for Unicode-safe modifications.
go
package main
func main() {
s := "hello"
// s[0] = 'H' // This line causes compile error: cannot assign to s[0]
// Correct way:
b := []byte(s)
b[0] = 'H'
s2 := string(b)
println(s2) // Hello
}Output
Hello
Quick Reference
| Concept | Details |
|---|---|
| String immutability | Strings cannot be changed after creation |
| Modify string | Convert to []byte or []rune, change, then convert back |
| Direct assignment | Not allowed, causes compile error |
| Unicode safety | Use []rune for multi-byte characters |
| String declaration | var s string = "text" or s := "text" |
Key Takeaways
Strings in Go are immutable and cannot be changed after creation.
To modify a string, convert it to a []byte or []rune, change it, then convert back.
Directly assigning to string indexes causes compile errors.
Use []rune for safe modification of Unicode characters.
Always create new strings instead of trying to alter existing ones.