0
0
GoHow-ToBeginner · 2 min read

Go How to Convert String to Rune Slice Easily

In Go, you can convert a string to a rune slice by using runes := []rune(yourString), which creates a slice of runes representing each Unicode character.
📋

Examples

Input"hello"
Output[104 101 108 108 111]
Input"Go语言"
Output[71 111 35821 35328]
Input""
Output[]
🧠

How to Think About It

To convert a string to a rune slice, think of the string as a sequence of characters. Each character can be represented as a rune, which is Go's way to handle Unicode characters. By converting the string to a rune slice, you get each character separately, including multi-byte characters.
📐

Algorithm

1
Take the input string.
2
Use the conversion syntax to cast the string to a rune slice.
3
Store the result in a variable.
4
Return or use the rune slice as needed.
💻

Code

go
package main

import (
	"fmt"
)

func main() {
	str := "Go语言"
	runes := []rune(str)
	fmt.Println(runes)
}
Output
[71 111 35821 35328]
🔍

Dry Run

Let's trace the string "Go语言" through the code

1

Input string

str = "Go语言"

2

Convert to rune slice

runes = []rune(str) => [71 111 35821 35328]

3

Print rune slice

Output: [71 111 35821 35328]

IndexCharacterRune Value
0G71
1o111
235821
335328
💡

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

Using a for range loop to append runes
go
package main

import (
	"fmt"
)

func main() {
	str := "Go语言"
	var runes []rune
	for _, r := range str {
		runes = append(runes, r)
	}
	fmt.Println(runes)
}
This method builds the rune slice manually and is useful if you want to process runes during conversion but is less concise.

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.

ApproachTimeSpaceBest For
Direct conversion ([]rune(str))O(n)O(n)Simple and fast conversion
Manual loop with appendO(n)O(n)Processing runes during conversion
💡
Use []rune(yourString) to convert strings to rune slices quickly and safely handle Unicode characters.
⚠️
Trying to convert a string to a byte slice instead of a rune slice, which breaks multi-byte characters.