This question already has answers here:
Creating a vector of zeros for a specific size
(4 个回答)
6年前关闭。
访问
我现在能做的最好的事情是预先分配一个向量,然后推出它的长度,但这不可能是惯用的。
或者使用迭代器:
(4 个回答)
6年前关闭。
访问
&mut [u8]
的最有效方法是什么?现在我从 Vec 借用,但更直接地分配缓冲区会更容易。我现在能做的最好的事情是预先分配一个向量,然后推出它的长度,但这不可能是惯用的。
let mut points_buf : Vec<u8> = Vec::with_capacity(points.len() * point::POINT_SIZE);
for _ in (0..points_buf.capacity()) {
points_buf.push(0);
}
file.read(&mut points_buf[..]).unwrap();
最佳答案
您可以直接创建具有给定大小的 vec:
vec![0; num_points]
或者使用迭代器:
repeat(0).take(num_points).collect::<Vec<_>>()
关于buffer - 在 Rust 中创建字节缓冲区,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30749918/