Skip to content

Vec::is_empty

Vec methods · Collections

Level: reference · for working programmers

One line: Whether the vector has no elements.

pub const fn is_empty(&self) -> bool

Stable since 1.0.0. Callable in a const context since 1.87.0.

Exactly len() == 0, and the spelling to prefer — clippy::len_zero is warn-by-default about the long form.

Empty is about length, never about allocation. A Vec::with_capacity(64) is empty. A vector that held a thousand elements and was cleared is empty and still holds the buffer. is_empty() and capacity() == 0 are different questions.

It is the guard that makes indexing safe — but the Option-returning accessors (first, last, get) usually say it better, because they answer the question and produce the value in one step.

A Vec<Vec<T>> of empty vectors is not itself empty: the outer length is what is measured.

Example

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

fn main() {
    let empty: Vec<i32> = Vec::new();
    let full = vec![1];
    println!("{} {}", empty.is_empty(), full.is_empty());

    // Exactly `len() == 0`, spelled so it reads.
    println!("same answer: {}", empty.is_empty() == (empty.len() == 0));

    // Empty is about LENGTH, never about capacity or allocation.
    let mut v: Vec<u8> = Vec::with_capacity(64);
    println!("cap 64 and still empty: {}", v.is_empty());
    v.push(1);
    v.clear();
    println!("cleared: empty {} but cap {}", v.is_empty(), v.capacity());

    // The guard that makes indexing safe.
    let v: Vec<i32> = vec![];
    if !v.is_empty() { println!("{}", v[0]); } else { println!("nothing to index"); }

    // Usually you want the Option-returning form instead of a guard.
    println!("first {:?} last {:?}", v.first(), v.last());

    // A Vec of empty vectors is not itself empty.
    let rows: Vec<Vec<u8>> = vec![vec![], vec![]];
    println!("outer empty {} inner all empty {}",
             rows.is_empty(), rows.iter().all(|r| r.is_empty()));

    // clippy::len_zero is the lint that pushes you here.
    let names = vec!["Ada"];
    if !names.is_empty() { println!("{} name(s)", names.len()); }
}

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

true false
same answer: true
cap 64 and still empty: true
cleared: empty true but cap 64
nothing to index
first None last None
outer empty false inner all empty true
1 name(s)

See also

Vec::is_empty in the standard library ↗