rust - 为什么当我推送的元素多于 Vec 的容量时没有错误?

标签 rust

我遇到了这个潜在的错误:

#[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. If capacity 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/

相关文章:

generics - 为两步从创建通用的“从/到”快捷方式

rust - 为什么 io::copy 要求读者和作者都是可变引用?

rust - 在Rust中挣扎着悬而未决的引用和静态生命周期建议

GDB 在 Rust 可执行文件中找不到调试符号

rust - Visual Studio Code 中没有 Rust 自动完成外部包装箱,例如 'gtk-rs'

rust - 在Rust中的元组中传递多个引用

rust - 如何创建在应用的操作中通用的 Rust 函数?

compiler-construction - 写语法扩展时,是否可以查询注解类型以外的类型信息?

rust - 带有删除的双向链表?

rust - 如何声明一个函数而不实现它?