实现说明
with_capacity 预分配 Vec 容量可以归结为函数 main。
文件的主干是一个循环——for i in 0..4。
使用要点
- 跑完文件,输出里会留下标记——
empty but cap=、len=、after growth len=。
常见问题
运行「with_capacity 预分配 Vec 容量」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 empty but cap=、len=、after growth len= 这类标签。
核心语句
let mut buffer = Vec::with_capacity(4);
buffer.shrink_to_fit();
buffer.push(i * 10);
代码示例
fn main() {
// When the element count is known: with_capacity allocates once, so pushes stop re-growing
let mut buffer = Vec::with_capacity(4);
println!("empty but cap={}", buffer.capacity());
for i in 0..4 {
buffer.push(i * 10);
}
println!("len={} cap={}", buffer.len(), buffer.capacity());
// Reallocation fires only past capacity: growth follows the Vec growth strategy
buffer.push(40);
println!("after growth len={} cap={}", buffer.len(), buffer.capacity());
// reserve guarantees room for at least that many additional elements
buffer.reserve(100);
println!("after reserve cap={}", buffer.capacity());
// shrink_to_fit hands back the excess capacity
buffer.shrink_to_fit();
println!("shrunk cap={}", buffer.capacity());
}