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:
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:
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:
("Type: ", reflect.TypeOf(r1))
str := "Hello world👋"
str_rune := rune(str)
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:
The previous code should return the string from the rune.
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.