Rune In Go

In Go, a rune is an alias for the int32 type, and it represents a Unicode code point. It is used to represent a single Unicode character. Go uses UTF-8 encoding for strings, and a rune represents a single Unicode code point in that encoding.

Here are a few examples to illustrate the concept of rune in Go:

Example 1: Iterate over a string using range to access individual runes:

package main

import "fmt"

func main() {
    str := "Hello, 世界!" // Contains characters from different languages

    for _, r := range str {
        fmt.Printf("%c ", r) // Print each rune
    }
}

Output:

H e l l o ,   世 界 !

In this example, we iterate over the string str using range. The range returns each character of the string as a rune. We can then print each rune using %c format specifier, which represents the Unicode character associated with the given code point.

Example 2: Convert a rune to an int to get the Unicode code point:

package main

import "fmt"

func main() {
    r := '世' // Rune representing the character '世'

    codePoint := int(r) // Convert the rune to int

    fmt.Println(codePoint) // Print the Unicode code point
}

Output:

19990

In this example, we have a rune representing the character ‘世’. By converting the rune to an int, we obtain the Unicode code point associated with that character.

The use of rune type is particularly helpful when dealing with Unicode characters, as it allows you to handle and process individual characters irrespective of their encoding. It provides a convenient way to work with Unicode strings in Go.