typestar

Characters and bytes in Rust

A char is a Unicode scalar; bytes are something else, and Rust keeps them apart.

fn main() {
    let word = "Rust!";
    println!("{} chars, {} bytes", word.chars().count(), word.len());

    for c in word.chars() {
        if c.is_alphabetic() {
            print!("{}", c.to_ascii_uppercase());
        }
    }
    println!();

    let digit = '7';
    println!("{:?}", digit.to_digit(10));
}

How it works

  1. chars() walks scalars, bytes() walks the UTF-8 bytes.
  2. is_alphabetic and friends classify a char.
  3. to_ascii_uppercase avoids the locale question entirely.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
257
Tokens
90
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 68 seconds.

Type this snippet

Step 6 of 6 in Variables & types, step 6 of 39 in Language basics.

← Previous Next →