golang

Golang Rune

In the Go programming language, a rune is an alias for int32 data type used to represent Unicode code points. This article highlights what runes are, and how we can use them in a Go program.

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:

package main
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:

$ go run runes.go
Unicode(r1): U+0041
Unicode(r2): U+1F44B
Unicode(r3): U+4EBA
Unicode(r4): U+0414

We can check the type as:

fmt.Println("Type: ", reflect.TypeOf(r1))

The snippet should return the data type as:

Type: int32

Golang Convert String to Rune

We can create a rune from strings as shown in the program below:

package main
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:

[U+0048 U+0065 U+006C U+006C U+006F U+0020 U+0077 U+006F U+0072 U+006C U+0064 U+1F44B]

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:

str := string([]rune{'\u0048','\u0065','\u006C','\u006C','\u006F'})

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list