Convert String to Rune SliceConvert a string into a rune slice and then call append to add a rune to it.
This page was last reviewed on Oct 8, 2022.
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.
Shows a slice
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 example. 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.
Detail In this Golang program we modify the first character in a string, and then add a fourth character to the end.
Shows a slice
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
Substrings, notes. Rune slices are also ideal for acquiring substrings from a string. This supports Unicode characters with no risk of data corruption.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 8, 2022 (image).
© 2007-2024 Sam Allen.