Skip to content

String::len

String methods · Strings

Level: reference · for working programmers

One line: The number of bytes, not characters — the same count as str::len, reached through the same deref.

pub const fn len(&self) -> usize

Stable since 1.0.0. Usable in a const context.

String derefs to str, so this is that method; the inherent version exists so it is const and so it appears where people look for it.

It counts the UTF-8 bytes actually written — len(), not capacity(). The two differ whenever there is spare room, and only len is part of the value.

Everything the str page says applies: chars().count() is the character count and is O(n), a byte offset is not a character position, and this is the number a slice endpoint is measured in.

Example

string_len.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let s = String::from("héllo");
    println!("len {} chars {}", s.len(), s.chars().count());

    // len is what is written; capacity is what is available.
    let mut roomy = String::with_capacity(64);
    roomy.push_str("héllo");
    println!("len {} capacity {}", roomy.len(), roomy.capacity());

    // The same count as the str method.
    println!("{}", s.len() == s.as_str().len());

    // Bytes grow by more than one per character.
    let mut built = String::new();
    for c in ['a', 'é', '👋'] {
        built.push(c);
        println!("after {c:?}: len {}", built.len());
    }
}

Verified output of string_len.rs — regenerated by tools/run_examples.py, never hand-typed.

len 6 chars 5
len 6 capacity 64
true
after 'a': len 1
after 'é': len 3
after '👋': len 7

See also

String::len in the standard library ↗

Po polsku

len liczy bajty, nie znaki, a dla polskiego tekstu ta różnica przestaje być teoretyczna już przy pierwszym słowie: "Zażółć".len() to 10, podczas gdy "Zażółć".chars().count() to 6, bo ż, ó, ł i ć zajmują po dwa bajty każdy — dokładnie to samo, co strona pokazuje na "héllo" wierszem len 6 chars 5. Kto przychodzi z Pythona, gdzie len("Zażółć") daje po prostu 6, musi tę intuicję odwrócić: w Ruscie długość w znakach liczy się jawnie, przez chars().count(), i jest to operacja O(n), bo trzeba przejść cały łańcuch znaków od początku. Nie myl też len() z capacity() — pierwsze mówi, ile treści jest zapisanej, i należy do wartości; drugie mówi tylko, ile miejsca wynajęto na stercie (stąd len 6 capacity 64 w przykładzie).

Szukaj po polsku: długość łańcucha w bajtach · polskie znaki w UTF-8 · liczba znaków a liczba bajtów · rust String len bytes not chars · rust chars count