【问题标题】:Vec<T>, vector of intergers vs vector of String, why can I index/copy int element even if the elements are on the heap? [duplicate]Vec<TO>,整数向量与字符串向量,为什么即使元素在堆上,我也可以索引/复制 int 元素? [复制]
【发布时间】:2020-09-02 22:51:52
【问题描述】:

简而言之,一些数据类型存储在堆栈中,因为编译器知道它们在运行时需要多少内存。其他数据类型更灵活,并且存储在堆中。数据的指针停留在栈上,指向堆数据。

我的问题是,如果 Vec 数据在堆上,如何访问 i32(和其他通常在堆栈中存储的类型),就好像它们实际上在堆栈上一样(通过索引复制)。

换句话说。对我来说,我不能 move 从 Vec 中取出字符串是有道理的,它们没有实现 Copy 并且通常是 move。当它们是 Vec 的元素时,也会发生同样的情况。不过 i32 通常是被复制的,但是为什么当它们是堆上的向量数据的一部分时也会发生这种情况呢?

如果您认为我遗漏了某些内容,请随时指出任何概念性错误并指出我现有的材料。我已经阅读了 Rust 编程语言并检查了一下。

fn main() {
    // int in stack
    let i: i32 = 1;
    let _ic = i;
    println!("{}", i);

    // String on heap
    let s: String = String::from("ciao cippina");
    let _sc = &s;
    println!("{}", s);

    // array and data on the stack
    let ari = [1, 2, 3];
    println!("{:?}", &ari);
    println!("a 0 {}", ari[0]);

    // array and Pointers on the stack, data on the heap
    let ars = [String::from("ciao"), String::from("mondo")];
    println!("{:?}", &ars);
    println!("a 0 {}", ars[0]);
    // let _ars_1 = ars[0];  // ERROR, cannot move out of array

    // Vec int, its Pointer on stack, all the rest on heap
    let veci = vec![2, 4, 5, 6];
    println!("{:?}", &veci);
    println!("a 0 {}", veci[0]);
    let _veci_1 = veci[0];  // NO ERROR HERE ??

    // Vec string, its Pointer on stack, all the rest on heap
    let vecs = vec![String::from("ciao"), String::from("mondo")];
    println!("{:?}", &vecs);
    println!("a 0 {}", vecs[0]);
    // let _vecs_1 = vecs[0];  // ERROR, cannot move out of Vec
}

【问题讨论】:

  • 是的,动机与 Vivek 在这里指出的相同。我想我的想法很糟糕,即从堆中复制速度较慢,因此无论类型如何(可复制与否),移动都是首选。谢谢大家的cmets和回答。

标签: rust collections heap-memory


【解决方案1】:

仅仅因为向量的元素存在于堆上并不意味着编译器无法知道元素的大小。元素的位置无关紧要,如果一个类型是“可复制的”,它可以从堆栈 -> 堆复制,反之亦然。

在您的情况下,i32 无论是在堆上还是在堆栈上都占用 4 个字节(忽略对齐问题)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 2016-02-15
    • 1970-01-01
    • 2018-08-04
    相关资源
    最近更新 更多