liveBook · Manning

Char(n)

As explained in Learn Rust in a Month of Lunches

Rust's char type represents one Unicode scalar value and occupies four bytes.

In Rust, `char` holds one Unicode scalar value. Write a character between single quotes: `let letter = 'A';`. A space, a character from another language, and an emoji can each be a `char` too. section 1.3

A `char` always occupies four bytes. That does not mean the same character takes four bytes in a string: UTF-8 uses different numbers of bytes for different characters. For example, the strings `"a"`, `"ß"`, `"国"`, and `"𓅱"` have lengths of one, two, three, and four bytes respectively. section 1.3

fn main() {
    println!("Size of a char: {}", std::mem::size_of::<char>());
    println!("Size of a: {}", "a".len());
    println!("Size of ß: {}", "ß".len());
    println!("Size of 国: {}", "国".len());
    println!("Size of 𓅱: {}", "𓅱".len());
}

Run this example to compare the fixed size of `char` with the byte lengths of four one-character strings. section 1.3

When counting characters in a string, use `.chars().count()` rather than `.len()`: `.len()` counts bytes. For an individual `char`, `.len_utf8()` reports how many bytes it would use in UTF-8. Methods such as `.is_whitespace()` can inspect it, while `.escape_unicode()` shows its Unicode number. section 1.3 section 20.2

You can make a `char` from a `u8` with `char::from()`. Conversion from a `u32` uses `char::try_from()` because not every `u32` value represents a character. If a direct `as char` cast of an ordinary number produces a compiler error, check its integer type: only `u8` can be cast directly to `char`. section 1.3 section 20.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines `char`, works through storage and conversion examples, then surveys selected methods without cataloging them all.
Examples
Shows quoted characters, byte-size comparisons, a failed integer cast, Unicode escapes, and conversions from integers.
What it assumes
Introduces primitive types and bytes before explaining `char`; assumes no prior Unicode terminology.
What you can do after
Evaluate/understand it by distinguishing fixed-size `char` storage from UTF-8 byte lengths and choosing character counts when needed.
How it connects
Connects `char` to Unicode, UTF-8, string slices, integer types, `From`, and `TryFrom`.

Also explained in

Compare how 5 books explain char(n) →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.