Vec resize_with Fills Generated Elements
Grow or shrink a Vec with resize_with, whose closure produces each new element from captured state, and observe that shrinking skips the closure entirely.
Code
fn main() {
let mut samples: Vec<usize> = Vec::new();
// resize_with:闭包按自己的捕获状态生成每个新元素
// 注意:闭包里不能借用 samples 本身(resize_with 需要 &mut self),
// 所以用独立的计数器变量,而不是读 samples.len()
let mut n = 0usize;
samples.resize_with(5, || {
n += 1;
n * 10
});
println!("grown: {:?}", samples);
// 缩小不调用闭包,直接丢弃尾部元素
samples.resize_with(3, || 999);
println!("shrunk: {:?}", samples);
// 再增长时同一个计数器从上次的位置继续
samples.resize_with(6, || {
n += 1;
n * 10
});
println!("regrown: {:?}", samples);
}Walkthrough of the flow
The logic concentrates in the function main.
What to watch for
- The only requirement is the runtime — nothing to install.
Putting it to use
The signature doing the work: fn main()
Look for the grown:, shrunk:, regrown: markers between the printed lines; each one marks a distinct step.
Lines that carry the behavior
let mut samples: Vec<usize> = Vec::new();
samples.resize_with(3, || 999);
let mut n = 0usize;
Interactive Tools for This Topic
FAQ
- What does Vec resize_with Fills Generated Elements print when run?
- The script runs standalone; its 3 labeled outputs include `grown:`, `shrunk:`, `regrown:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.