HomeSearch

Golang Convert String to Rune Slice (append)

Convert a string into a rune slice and then call append to add a rune to it.
String, rune slice. In Golang we often use strings to store character data. But rune slices have many advantages—they treat characters in a more consistent way.Strings
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.
Modify runes. 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.

And: We create a new string from the modified rune slice. This is character-based string manipulation in Go.

Golang program that modifies runes from string 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) } Output cat mate
Substrings, notes. Rune slices are also ideal for acquiring substrings from a string. This supports Unicode characters with no risk of data corruption.Substring
A summary. Converting a string to a rune slice in Golang is a common operation. It leads to code that will be less likely to corrupt Unicode characters.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls