Golang: Rune
What is Rune
Rune means Unicode Code Point. (think of it as a character type.) It is a jargon golang invented.
A rune is ALL of the following. Which meaning you pick depends on context:
- A integer, with possible values from 0 to 2^32 -1.
- A golang type, with keyword
rune. It is alias to the typeint32. - A Unicode Code Point.
- A character.
Purpose of Rune
The purpose of rune type is to directly represent one character. It is essentially a character type, just with a fancy name.
Rune Literal
A Rune Literal is a syntax to represent one Unicode character in golang.
Like this:
'c',
where the c is 1 single Unicode character. (but may be presented by escape sequence)
All of the following are rune values.
var capA = 'A'var heart = '♥'var butterfly = '🦋'var newline = '\n'〔see Golang: String Backslash Escape〕
package main import "fmt" func main() { // print a rune in decimal, hexadecimal, and standard unicode notation var xx = 'A' fmt.Printf("%d %x %U\n", xx, xx, xx) // 65 41 U+0041 }
Print Rune
Since a rune value is a integer, we can use Printf formats that converts integer to string.
%c-
print as the byte sequence of the character in Unicode: UTF-8 Encoding .
%q-
print in golang rune syntax. Sample output:
'a'. %U-
print in Unicode notation. Sample output:
U+03B1. %d-
print as integer in decimal notation.
%x-
print as integer in Hexadecimal Notation.
package main import "fmt" // print rune in different formats func main() { var x = '🦋' fmt.Printf("%c\n", x) // 🦋 fmt.Printf("%q\n", x) // '🦋' fmt.Printf("%U\n", x) // 1F602 fmt.Printf("%b\n", x) // 11111100110001011 fmt.Printf("%o\n", x) // 374613 fmt.Printf("%d\n", x) // 129419 fmt.Printf("%x\n", x) // 1f98b }
Rune Sequence
Value of rune type is just a single char.
For a sequence of chars, use Array or Slice. A slice of rune is common, and can be converted to string. 〔see Golang: String, Byte Slice, Rune Slice〕