String
, rune
sliceIn Go we often use strings to store character data. But rune
slices have many advantages—they treat characters in a more consistent way.
For Unicode characters, a rune
slice can be used to append and modify characters with no errors. If we act on a string
directly, we can cause problems here.
A string
contains runes (these are characters). We can convert a string
to a slice of runes. Then we can modify runes or add new ones.
string
from the modified rune
slice. This is character-based string
manipulation in Go.string
, and then add a fourth character to the end.package main import "fmt" func main() { original := "cat" fmt.Println(original) // Get rune slice. // ... Modify the slice's data. r := []rune(original) r[0] = 'm'; r = append(r, 'e') // Create new string from modified slice. result := string(r) fmt.Println(result) }cat mate
Rune slices are also ideal for acquiring substrings from a string
. This supports Unicode characters with no risk of data corruption.
Converting a string
to a rune
slice in Go is a common operation. It leads to code that will be less likely to corrupt Unicode characters.