String, rune slice. In 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.
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 Go program we modify the first character in a 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
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 Go is a common operation. It leads to code that will be less likely to corrupt Unicode characters.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 8, 2022 (image).