Convert rune array/slice to string (and back)

yourbasic.org/golang

String to rune slice

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]

You can also use a range loop to access the code points of a string.

Rune slice to string

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

Performance

These conversions create a new slice or string, and therefore have time complexity proportional to the number of bytes that are processed.

A string builder can be used to efficiently concatenate strings without redundant copying. See How to best use a string builder.

Further reading

String functions cheat sheet

Share this page: