【发布时间】: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