Rust Char
A char is a Rust type for one character. A char takes four bytes.
One character, single quotes
Write a char in single quotes. It holds exactly one character:
let letter = 'R';
let heart = '❤';
println!("{} {}", letter, heart);Every char takes four bytes
Ask a char how many bytes it needs in text form with len_utf8. Simple letters need one. An emoji needs all four:
println!("a bytes = {}", 'a'.len_utf8());
println!("crab bytes = {}", '🦀'.len_utf8());Write a char by its Unicode number
Every char has a Unicode number. The \u{...} form writes a char by that number, and as u32 reads the number back:
let crab = '\u{1F980}';
println!("crab = {}", crab);
println!("A code = {}", 'A' as u32);Ask a char what it is
A char can describe itself, and it can change its own case:
let c = 'r';
println!("letter? {} digit? {}", c.is_alphabetic(), c.is_ascii_digit());
println!("shout = {}", c.to_uppercase());Chars are not bytes
Walk a text with .chars() to count its characters. The byte count can be bigger, because some letters take more than one byte:
let word = "héllo";
println!("chars = {}", word.chars().count());
println!("bytes = {}", word.len());Example
fn main() {
let a = 'R';
let crab = '🦀';
let seven = '7';
println!("{} a letter? {}", a, a.is_alphabetic());
println!("{} takes {} bytes as text", crab, crab.len_utf8());
println!("{} a digit? {}", seven, seven.is_ascii_digit());
println!("héllo has {} chars", "héllo".chars().count());
}Key points
- String text uses double quotes.
- A char uses single quotes.
- So 'a' is a char.
- And "a" is text.
- Every char is 4 bytes, whatever it holds.
- One byte letters are the same size as values.
- Four byte emoji are too.
- Use text.chars() to walk a text one char at a time — the Strings lesson builds on this
- A char can hold a letter from any language.
- A char can also hold a digit.
In this example, each char is asked the questions from this lesson. R is a letter, so is_alphabetic answers true. The crab needs all four bytes in text form, and len_utf8 reports 4. The char 7 is a digit, so is_ascii_digit answers true. The last line counts the chars in "héllo": five chars, even though the text takes six bytes. Asking each char what it is — that is how real programs check passwords and clean up typed text.
Note
One char is one Unicode scalar value.
It is not always one visible letter.
Some written letters are a base char plus a combining mark.
Rust counts those as two chars.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
How big is one Rust char, and what can it hold?