Go How to Convert String to Rune Slice Easily
runes := []rune(yourString), which creates a slice of runes representing each Unicode character.Examples
How to Think About It
Algorithm
Code
package main import ( "fmt" ) func main() { str := "Go语言" runes := []rune(str) fmt.Println(runes) }
Dry Run
Let's trace the string "Go语言" through the code
Input string
str = "Go语言"
Convert to rune slice
runes = []rune(str) => [71 111 35821 35328]
Print rune slice
Output: [71 111 35821 35328]
| Index | Character | Rune Value |
|---|---|---|
| 0 | G | 71 |
| 1 | o | 111 |
| 2 | 语 | 35821 |
| 3 | 言 | 35328 |
Why This Works
Step 1: String as Unicode
A Go string holds bytes, but characters can be multi-byte Unicode. Using []rune converts the string into Unicode code points.
Step 2: Rune slice creation
The conversion []rune(str) creates a slice where each element is a rune representing one character.
Step 3: Use of rune slice
You can now access, modify, or iterate over characters safely, even if they are multi-byte.
Alternative Approaches
package main import ( "fmt" ) func main() { str := "Go语言" var runes []rune for _, r := range str { runes = append(runes, r) } fmt.Println(runes) }
Complexity: O(n) time, O(n) space
Time Complexity
Converting a string to a rune slice requires scanning each character once, so it takes linear time proportional to the string length.
Space Complexity
A new slice is created to hold all runes, so space used grows linearly with the number of characters.
Which Approach is Fastest?
Direct conversion with []rune(str) is the fastest and simplest. Manual looping is more flexible but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct conversion ([]rune(str)) | O(n) | O(n) | Simple and fast conversion |
| Manual loop with append | O(n) | O(n) | Processing runes during conversion |
[]rune(yourString) to convert strings to rune slices quickly and safely handle Unicode characters.