try_reserve Returns Capacity Errors

Ask for collection capacity with try_reserve and match TryReserveError, so capacity overflow becomes a recoverable branch instead of a process abort.

RustResilience

Code

rustsnippet
24 lines
use std::collections::HashMap;

fn main() {
    // try_reserve:容量申请失败返回错误值,而不是中止进程
    let mut rows: Vec<u8> = Vec::new();
    match rows.try_reserve_exact(1_000_000) {
        Ok(()) => println!("reserved, capacity now {}", rows.capacity()),
        Err(e) => println!("reserve failed: {:?}", e),
    }

    // 超过 isize 上限:CapacityOverflow 是确定性失败,可按分支处理
    let mut runaway: Vec<u8> = Vec::new();
    match runaway.try_reserve(usize::MAX) {
        Ok(()) => println!("impossible"),
        Err(e) => println!("overflow classified: {:?}", e),
    }

    // HashMap 同样提供 try_reserve:预分配容量避免反复扩容
    let mut index: HashMap<String, u32> = HashMap::new();
    match index.try_reserve(1_000) {
        Ok(()) => println!("map ready"),
        Err(e) => println!("map reserve failed: {:?}", e),
    }
}

What the code does

All of the logic lives in the function main.

Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Points of care

  • Copy, run: the standard library answers every call in the file.

Applying it

The main signature reads fn main()

Each run prints the 6 labeled blocks reserved, capacity now, reserve failed:, impossible, overflow classified:, map ready, map reserve failed: in source order.

Statements that matter

match rows.try_reserve_exact(1_000_000) {
Ok(()) => println!("reserved, capacity now {}", rows.capacity()),
Err(e) => println!("reserve failed: {:?}", e),
}
match runaway.try_reserve(usize::MAX) {
Ok(()) => println!("impossible"),
Err(e) => println!("overflow classified: {:?}", e),
}
match index.try_reserve(1_000) {
Ok(()) => println!("map ready"),
Err(e) => println!("map reserve failed: {:?}", e),
}

Interactive Tools for This Topic

FAQ

What does try_reserve Returns Capacity Errors print when run?
Execute the whole file; each printed line is prefixed with a label like `reserved, capacity now`, `reserve failed:`, `impossible`.