What Is the Difference Between chars() and bytes() in Rust?

chars() iterates over Unicode characters while as_bytes() iterates over raw UTF-8 bytes.

The chars() method iterates over Unicode scalar values (graphemes), while as_bytes() (often used with .iter()) iterates over raw UTF-8 bytes.

fn main() {
    let s = "Hello";
    // Iterates over characters: 'H', 'e', 'l', 'l', 'o' (5 items)
    for c in s.chars() {
        println!("Char: {}", c);
    }

    // Iterates over bytes: 72, 101, 108, 108, 111 (5 items for ASCII)
    for b in s.as_bytes() {
        println!("Byte: {}", b);
    }

    // With non-ASCII: "café" has 4 chars but 5 bytes
    let s2 = "café";
    println!("Chars: {}", s2.chars().count()); // 4
    println!("Bytes: {}", s2.as_bytes().len()); // 5
}