liveBook · Manning

Rune

As explained in Go in Practice, Second Edition

A rune is Go's integer type for representing a Unicode code point.

A rune is Go’s integer type for representing a Unicode code point. Use a slice of runes when processing characters whose UTF-8 representation may occupy multiple bytes; indexing the original string as bytes can corrupt operations such as reversal. section 1.2.4

Reverse a name safely

A byte-based reversal can produce invalid output for a non-ASCII name. Convert the string to []rune, iterate over the rune slice backward, append each rune, and convert the result back to a string. Running go test then verifies the corrected behavior. section 1.2.4

func reverseNameFixed(name string) string {
    reversed := make([]rune, 0)
    runes := []rune(name)
    for i := len(runes) - 1; i >= 0; i-- {
        reversed = append(reversed, runes[i])
    }
    return string(reversed)
}

Shows the complete rune-slice implementation for reversing a string. section 1.2.4

How Go in Practice, Second Edition covers it

How deep it goes
Defines the Unicode-code-point type and demonstrates conversion to []rune, stopping short of deeper Unicode internals.
Examples
Demonstrates reversing an ASCII name and a name containing a non-ASCII character, then validating the fix with go test.
What it assumes
Assumes basic Go strings, slices, functions, and tests while clarifying why byte indexing fails for multibyte characters.
What you can do after
Diagnose and fix character-processing bugs by converting strings to rune slices before character-wise operations.
How it connects
Ties runes to strings, Unicode, UTF-8 multibyte characters, and Go testing.

Also explained in

Compare how 4 books explain rune →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.