我遇到了这个潜在的错误:
#[derive(Debug)]
enum StackType {
Int(i64),
Float(f64),
Word(String),
}
fn main() {
let mut stack: Vec<StackType> = Vec::with_capacity(1);
stack.push(StackType::Int(5));
stack.push(StackType::Float(5_f64));
stack.push(StackType::Word(String::from("ABC")));
println!("{:?}", stack);
}
我在 Windows 10 上使用 Rust v1.26.0 (a77568041 2018-05-07)。
当我编译并运行上面的程序时,我预计会出现错误,因为指定的容量为 1,并且我已经使用了 3 次推送,但输出是正确的:
[Int(5), Float(5.0), Word("ABC")]
最佳答案
Vec
可以动态增长,类似于C++的std::vector
.您指定 with_capacity
的事实只是意味着它可以在不重新分配的情况下容纳那么多元素。查看documentation for Vec::with_capacity
:
Constructs a new, empty
Vec<T>
with the specified capacity.The vector will be able to hold exactly
capacity
elements without reallocating. Ifcapacity
is 0, the vector will not allocate.It is important to note that although the returned vector has the capacity specified, the vector will have a zero length. For an explanation of the difference between length and capacity, see Capacity and reallocation.
这是来自 Vec
的摘录关于 Capacity and Reallocation 的文档:
The capacity of a vector is the amount of space allocated for any future elements that will be added onto the vector. This is not to be confused with the length of a vector, which specifies the number of actual elements within the vector. If a vector's length exceeds its capacity, its capacity will automatically be increased, but its elements will have to be reallocated.
For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10 more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or cause reallocation to occur. However, if the vector's length is increased to 11, it will have to reallocate, which can be slow. For this reason, it is recommended to use
Vec::with_capacity
whenever possible to specify how big the vector is expected to get.
这不同于 fixed-length array不能超过规定的长度。
关于rust - 为什么当我推送的元素多于 Vec 的容量时没有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50493989/