Golang: Rune

By Xah Lee. Date: . Last updated: .

What's Rune

“Rune” means Unicode codepoint. (think of it as a character.) It is a jargon golang invented.

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

[see Golang: Basic Types]

Purpose of Rune

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

What's Codepoint

Unicode gives each character a integer id. This integer id is called codepoint.

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

Unicode Standard Notation for Codepoint

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 one Unicode character. Like this:

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

All of the following are rune values.

To see all backslash escapes, see Golang: String Backslash Escape

Print a rune in decimal, hex, and standard unicode notations

package main

import "fmt"

func main() {

	// print a rune in decimal, hex, and standard unicode notations

	var capA = 'A'

	fmt.Printf("%d %x %U\n", capA, capA, capA) // 65 41 U+0041
}

Print Rune

Rune is codepoint, thus is a integer.

The following Printf formats work with integer:

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) // 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
}

Rune Sequence?

Value of rune type is just a single char.

For a sequence of chars, you use slice type instead. (Slice is a variable length array.) A slice of rune is common, and can be converted to string.

[see Golang: Slice]

[see Golang: String, Byte Slice, Rune Slice]

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. Source Encoding
  3. Package, Import
  4. Comment
  5. Print
  6. String
  7. Print String
  8. String Backslash Escape
  9. Rune
  10. Variable
  11. Zero Value
  12. Constant
  13. If Then Else
  14. Switch/Case
  15. Loop
  16. Basic Types
  17. Array
  18. Slice
  19. Map
  20. Struct
  21. Function
  22. Closure
  23. Pointer
  24. String, Byte Slice, Rune Slice
  25. regexp
  26. Read File
  27. Write to File
  28. Walk Dir
  29. Check File Exist
  30. System Call
  31. Get Script Path
  32. Defer
  33. Random Number

Examples

  1. Match Any Regexp
  2. Find Replace
  3. Validate Links
  4. Generate Sitemap

Reference

  1. Go Spec