String::try_reserve_exact¶
Level: reference · for working programmers
One line: reserve_exact returning Result — no round-up, and no abort on failure.
Stable since 1.57.0.
The fourth corner of the grid: exact or rounded, aborting or reporting.
| aborts | returns Result |
|
|---|---|---|
| rounds up | reserve ↗ |
try_reserve ↗ |
| exact | reserve_exact ↗ |
try_reserve_exact |
Use it where both properties matter at once: a size that came from input (so failure must be handled) and is known to be final (so rounding up would waste memory that the input controls).
Example¶
string_try_reserve_exact.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let mut s = String::from("ab");
println!("{:?}", s.try_reserve_exact(5).is_ok());
println!("capacity {}", s.capacity());
// The four corners, side by side.
let mut a = String::from("ab"); a.reserve(5);
let mut b = String::from("ab"); b.reserve_exact(5);
let mut c = String::from("ab"); c.try_reserve(5).unwrap();
let mut d = String::from("ab"); d.try_reserve_exact(5).unwrap();
println!("reserve {} / reserve_exact {} / try_reserve {} / try_reserve_exact {}",
a.capacity(), b.capacity(), c.capacity(), d.capacity());
// Failure is a value, not a process kill.
let mut huge = String::new();
println!("{:?}", huge.try_reserve_exact(usize::MAX).is_err());
println!("still usable: {:?}", { huge.push_str("ok"); &huge });
}
Verified output of string_try_reserve_exact.rs — regenerated by tools/run_examples.py, never hand-typed.
true
capacity 7
reserve 8 / reserve_exact 7 / try_reserve 8 / try_reserve_exact 7
true
still usable: "ok"
See also¶
String::try_reserve— with the round-upString::reserve_exact— the aborting versionString::shrink_to_fit— the other direction
String::try_reserve_exact in the standard library ↗
Po polsku¶
Najłatwiej zapamiętać tę czwórkę jako siatkę dwa na dwa: jedna oś to „z zaokrągleniem albo dokładnie”, druga to „przerywa proces albo zwraca Result” — a try_reserve_exact zajmuje ostatni róg. Różnicę widać w liczbach z przykładu: dla dwuznakowego łańcucha znaków i prośby o 5 warianty zaokrąglające dają pojemność 8, a dokładne 7. Po tę metodę sięga się wtedy, gdy zależy nam na obu tych zachowaniach naraz: rozmiar przyszedł z wejścia (więc porażkę trzeba obsłużyć) i jest ostateczny (więc zaokrąglanie marnowałoby pamięć, o której rozmiarze decyduje ktoś z zewnątrz). Po nieudanej próbie String pozostaje w pełni sprawny — w przykładzie od razu przyjmuje push_str.
Szukaj po polsku: rezerwowanie pojemności · dokładna alokacja bez zaokrąglania · rust try_reserve_exact · rust reserve vs reserve_exact