String::is_empty¶
Level: reference · for working programmers
One line: true when len() is 0 — and note that a capacity of any size does not make a string non-empty.
Stable since 1.0.0. Usable in a const context.
The same test as str::is_empty, reached by deref. A String::with_capacity(1024) is empty; a String that has been cleared is empty and still owns its buffer.
The usual caution applies: a string of spaces is not empty, so input handling wants s.trim().is_empty(). And "empty" is not "absent" — if a value can legitimately be missing, that is Option<String>.
Example¶
string_is_empty.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
println!("{}", String::new().is_empty());
println!("{}", String::from("x").is_empty());
// Capacity does not make it non-empty.
let roomy = String::with_capacity(1024);
println!("capacity {} but empty: {}", roomy.capacity(), roomy.is_empty());
// clear() empties it while keeping the buffer.
let mut used = String::from("hello");
used.clear();
println!("empty {} capacity {}", used.is_empty(), used.capacity());
// Blank is not empty.
let blank = String::from(" ");
println!("{} {}", blank.is_empty(), blank.trim().is_empty());
// Empty is not missing.
let values: [Option<String>; 3] = [Some("v".into()), Some("".into()), None];
for v in values {
let verdict = match &v {
None => "absent",
Some(s) if s.is_empty() => "present but empty",
Some(_) => "present",
};
println!("{v:?} -> {verdict}");
}
}
Verified output of string_is_empty.rs — regenerated by tools/run_examples.py, never hand-typed.
true
false
capacity 1024 but empty: true
empty true capacity 5
false true
Some("v") -> present
Some("") -> present but empty
None -> absent
See also¶
str::is_empty— the full explanationString::len— what this compares against zeroString::clear— the way to make a string empty without freeing itstr::trim— what to call first on human input
String::is_empty in the standard library ↗
Po polsku¶
is_empty odpowiada wyłącznie na pytanie „czy len() wynosi zero?”, a nie na pytanie, ile pamięci łańcuch znaków trzyma — String::with_capacity(1024) jest pusty, i po clear() też jest pusty, choć bufor o pojemności 5 wciąż do niego należy (wiersz empty true capacity 5 w wyniku). Warto rozdzielić dwie rzeczy, które w polszczyźnie zlewają się w jedno słowo „pusty”: łańcuch złożony z samych spacji pusty nie jest (przykład wypisuje false true — dopiero trim() to zmienia), a „pusty” to nie to samo co „brakujący” — nieobecność wartości modeluje się przez Option<String>, gdzie None znaczy „nie ma”, a Some("") „jest, tylko bez treści”. Kto przychodzi z SQL-a, ma gotową intuicję: to ta sama różnica co między NULL a '', z tą przyjemną zmianą, że tutaj pilnuje jej kompilator, a nie dokumentacja.
Szukaj po polsku: pusty łańcuch znaków · wartość pusta a brak wartości · białe znaki · rust String is_empty · rust trim is_empty