Chars Count Versus Byte Len

String len() counts UTF-8 bytes while chars().count() counts characters, and the gap decides password limits and text truncation.

RustForm Validation

Code

rustsnippet
16 lines
fn main() {
    let label = "café";
    let emoji = "🦀";

    // len() counts UTF-8 bytes versus chars().count(), which counts characters
    println!("{}: {} bytes", label, label.len());
    println!("{}: {} chars", label, label.chars().count());

    println!("{}: {} bytes", emoji, emoji.len());
    println!("{}: {} chars", emoji, emoji.chars().count());

    // char_indices exposes the real byte offset of each character
    for (byte_at, ch) in label.char_indices() {
        println!("byte {byte_at}: {ch}");
    }
}

How it works

Chars Count Versus Byte Len reduces to the function main.

Iteration happens inside for (byte_at, ch) in label.char_indices() — everything outside it runs once.

Putting it to use

Output lines are prefixed (byte), making each step’s effect easy to spot.

Core lines

let label = "café";
let emoji = "🦀";

Interactive Tools for This Topic

FAQ

What does Chars Count Versus Byte Len print when run?
No setup needed: run the file and look for labeled lines like `byte` in the output.