Convert string to/from rune slice

yourbasic.org/golang

String to rune slice

Converting a string to a slice of runes yields a slice whose elements are the Unicode code points of the string.

s := "abc日"
r := []rune(s)
fmt.Printf("%v\n", r) // [97 98 99 26085]
fmt.Printf("%U\n", r) // [U+0061 U+0062 U+0063 U+65E5]

Rune slice to string

Converting a slice of runes to a string yields a string that is the concatenation of the runes converted to UTF-8 encoded strings.

Values outside the range of valid Unicode code points are converted to \uFFFD, the Unicode replacement character .

r := []rune{'\u0061', '\u0062', '\u0063', '\u65E5', -1}
s := string(r)
fmt.Println(s) // abc日�

Further reading

String functions cheat sheet

Share this page: