What is the rune type in Golang

A rune in Go is a “data type that stores codes that represent Unicode characters.” Unicode is the collection of all possible characters present in the whole world.

Golang rune literals are 32-bit integer values (however, they are untyped constants, so their type can change). They represent the Unicode codepoints. “Rune” means Unicode codepoint. (think of it as a character.) It is a term golang invented.

Rune literal represents the rune constant where an integer value recognizes the Unicode code point. For example, the Rune literal ‘a’ is the number 97.

In the Go language, the Rune is expressed as one or more characters enclosed in single quotes like ‘g,’ ‘\t’, etc. You have allowed a place for any character except the new line and an unescaped single quote between quotes. A Golang string is a sequence of bytes in Golang.

UTF-8 encodes all Unicode between 1 to 4 bytes, where 1 byte is used for ASCII, and the rest is used for the Rune. ASCII contains a total of 256 elements. 128 are characters, and 0-127 are identified as code points. Here code point refers to the element which represents a single value.

Golang rune type is an alias for int32, indicating that an integer represents the code point. For example, ASCII defines 128 characters, identified by the code points 0–127.

UTF-8 encodes all the Unicode in 1 to 4 bytes, where 1 byte is used for ASCII and the rest for the Rune.

ASCII contains a total of 256 elements and out of which 128 are characters, and 0-127 are identified as code points. Here, code point refers to the element which represents a single value.

Rune literals

In Rune Literals, all the sequences that start with a backslash are illegal; only the following single-character escapes represent special values when you use them with a backslash: 

Character Unicode Description
\a U+0007 Alert or Bell
\b U+0008 backspace
\f U+000C form feed
\n U+000A line feed or newline
\r U+000D carriage return
\t U+0009 horizontal tab
\v U+000b vertical tab
\\ U+005c backslash
\’ U+0027 single-quote
\” U+0022 double quote(legal only in string literals)

Example 1

package main

import (
 "fmt"
)

func main() {
 fmt.Println([]byte("Garçon"))
 fmt.Println([]rune("Garçon"))
}

Output

[71 97 114 195 167 111 110]
[71 97 114 231 111 110]

Example 2

package main

import (
  "fmt"
  "reflect"
)

func main() {

  // Creating a rune
  runeK := 'K'
  runeb := 'b'
  runef := '\\'

  // Displaying rune and its type
  fmt.Printf("Rune 1: %c; Unicode: %U; Type: %s", runeK,
  runeK, reflect.TypeOf(runeK))

  fmt.Printf("\nRune 2: %c; Unicode: %U; Type: %s", runeb,
  runeb, reflect.TypeOf(runeb))

  fmt.Printf("\nRune 3: Unicode: %U; Type: %s", runef,
  reflect.TypeOf(runef))
}

Output

Rune 1: K; Unicode: U+004B; Type: int32
Rune 2: b; Unicode: U+0062; Type: int32
Rune 3: Unicode: U+005C; Type: int32

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.