A Little History
To better understand what is a rune, it is good to first understand what is a Unicode code point. It refers to a numerical value assigned to a Unicode character.
A few years back, we used a character set known as ASCII which uses 7 bits to represent 128 characters, including uppercase characters, numerical values, etc. However, the ASCII character set could not hold the plethora of languages and symbols of the entire world.
To solve this, the Unicode character encoding was invented. It is a superset of the ASCII character encoding and can hold up to 1114112 Unicode code points.
Golang Create Rune
We can declare a rune by enclosing the character inside a pair of single quotes. An example is shown below:
import"fmt"
funcmain() {
r1 := 'A'
r2 := '👋'
r3 := '人'
r4 := 'Д'
fmt.Printf("Unicode(r1): %U\n", r1)
fmt.Printf("Unicode(r2): %U\n", r2)
fmt.Printf("Unicode(r3): %U\n", r3)
fmt.Printf("Unicode(r4): %U\n", r4)
}
The previous code returns the Unicode code characters. An example output is as shown:
Unicode(r1): U+0041
Unicode(r2): U+1F44B
Unicode(r3): U+4EBA
Unicode(r4): U+0414
We can check the type as:
The snippet should return the data type as:
Golang Convert String to Rune
We can create a rune from strings as shown in the program below:
import (
"fmt"
)
funcmain() {
("Type: ", reflect.TypeOf(r1))
str := "Hello world👋"
str_rune := []rune(str)
fmt.Printf("%U\n", str_rune)
}
The previous code should return a slice of Unicode characters as shown in the output below:
Golang Convert Rune to String
We can also revert the previous operation and return a slice of runes back into a string. An example program is provided below:
fmt.Println(str)
The previous code should return the string from the rune.
Conclusion
In this guide, we discussed how to create and work with runes in the Go program. We hope you found this article helpful. Check other Linux Hint articles for more tips and tutorials.