Golang: Rune

By Xah Lee. Date: . Last updated: .

“Rune” means Unicode character. More precisely, it means a Unicode codepoint. It is a term golang invented.

When you see the word “rune”, you can think of it as any or all of the following:

[see Golang: Basic Types]

The purpose of rune is similar to character type in some other languages.

Unicode gives each character a integer id. This integer id is called codepoint. It can be expressed in decimal notation, also in hexadecimal notation.

Note, not all codepoint are character as we think of. For example, newline, tab, non-breaking-space, right-to-left mark, combining character accents, are all codepoints.

Unicode has a standard notation for codepoint, starting with U+ followed by its codepoint in hexadecimal. E.g.

Rune Literal

A “rune literal” is a syntax to represent 1 Unicode character. Like this:

'c' → rune literal. Where the c is 1 single Unicode character. (but may be presented by escape sequence) e.g.

to see all backslash escapes, see Golang: String

package main

import "fmt"

func main() {

    var capA = 'A'
    var heart = '♥'
    var omg = '😂'

    // decimal, hex, unicode notation
    fmt.Printf("%d, %x, %U\n", capA, capA, capA)    // 65, 41, U+0041
    fmt.Printf("%d, %x, %U\n", heart, heart, heart) // 9829, 2665, U+2665
    fmt.Printf("%d, %x, %U\n", omg, omg, omg)       // 128514, 1f602, U+1F602
}
package main

import "fmt"

// rune in different input forms

func main() {
    fmt.Printf("%U\n", '\n') // U+000A

    fmt.Printf("%v\n", '♥' == '\u2665')     // true
    fmt.Printf("%v\n", '😂' == '\U0001F602') // true
}

Print Rune

Rune is codepoint, thus is a integer.

The following format works with integer:

package main

import "fmt"

func main() {
    // var x = 'A'
    // var x = '♥'
    var x = '😂'

    fmt.Printf("%c\n", x) // 😂
    fmt.Printf("%q\n", x) // '😂'
    fmt.Printf("%U\n", x) // U+1F602

    fmt.Printf("%b\n", x) // 11111011000000010
    fmt.Printf("%o\n", x) // 373002
    fmt.Printf("%d\n", x) // 128514
    fmt.Printf("%x\n", x) // 1f602
}

Reference

The Go Programming Language Specification - The Go Programming Language#String_literals

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Package, Import
  3. Comment
  4. Print
  5. String
  6. Rune
  7. Variable
  8. Zero Value
  9. Constant
  10. If Then Else
  11. Switch/Case
  12. Loop
  13. Basic Types
  14. Array
  15. Slice
  16. Map
  17. Struct
  18. Function
  19. regexp
  20. Read File
  21. Write to File
  22. Walk Dir
  23. Check File Exist
  24. System Call
  25. Pointer
  26. Defer
  27. Random Number

Examples

  1. Validate Links
  2. Generate Sitemap

Reference

  1. Go Spec