What is rune in Go: Understanding Go's Character Type
rune is an alias for int32 that represents a Unicode code point, which means it holds a single character from any language. It is used to work with characters beyond simple ASCII, allowing Go programs to handle text with diverse symbols and languages.How It Works
Think of a rune as a box that can hold one character from any language in the world, not just English letters or numbers. Unlike a byte, which holds 8 bits and can only represent simple characters, a rune holds 32 bits, enough to store any Unicode character.
Unicode is like a giant dictionary that assigns a unique number to every character you can imagine, including emojis, accented letters, and symbols. In Go, a rune stores this number, so you can work with characters in a way that understands their true meaning, not just their raw bytes.
This makes runes very useful when you want to read, write, or manipulate text that includes special characters or languages other than English.
Example
This example shows how to declare a rune, print its value, and convert it to a string to see the character it represents.
package main import "fmt" func main() { var r rune = '世' // A Chinese character fmt.Println("Rune value:", r) // Prints the Unicode code point number fmt.Println("As character:", string(r)) // Converts rune to string to show the character }
When to Use
Use rune when you need to work with individual characters in text, especially if the text includes non-English letters, symbols, or emojis. For example, when counting characters, slicing strings by characters, or processing user input in multiple languages.
Since Go strings are sequences of bytes, using runes helps avoid mistakes when characters take more than one byte, like accented letters or emojis. This ensures your program handles text correctly and avoids bugs related to character encoding.
Key Points
- Rune is an alias for
int32in Go. - It represents a single Unicode code point (a character).
- Runes allow safe handling of characters beyond ASCII.
- Use runes to process text with special characters or multiple languages.
- Converting runes to strings shows the actual character.