我在Rust书中看到,您可以使用相同的名称定义两个不同的变量:
let hello = "Hello";
let hello = "Goodbye";
println!("My variable hello contains: {}", hello);
Run Code Online (Sandbox Code Playgroud)
打印出:
My variable hello contains: Goodbye
Run Code Online (Sandbox Code Playgroud)
第一次打招呼怎么了?它被释放了吗?我怎么能访问它?
我知道将两个变量命名为相同会很糟糕,但如果这种情况偶然发生,因为我将其声明为100行以下,这可能是一个真正的痛苦.
我想在一个中使用特征对象Vec.在C++中我可以使一个基类Thing从中导出Monster1和Monster2.然后我可以创建一个std::vector<Thing*>.Thing对象必须存储一些数据,例如x : int, y : int,派生类需要添加更多数据.
目前我有类似的东西
struct Level {
// some stuff here
pub things: Vec<Box<ThingTrait + 'static>>,
}
struct ThingRecord {
x: i32,
y: i32,
}
struct Monster1 {
thing_record: ThingRecord,
num_arrows: i32,
}
struct Monster2 {
thing_record: ThingRecord,
num_fireballs: i32,
}
Run Code Online (Sandbox Code Playgroud)
我定义了一个ThingTrait与方法get_thing_record(),attack(),make_noise()等,并实现它们的Monster1和Monster2.
在Rust Book,Variables和Mutability的第3章中,我们对这个主题进行了几次迭代,以演示Rust中变量的默认,不可变行为:
fn main() {
let x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
}
Run Code Online (Sandbox Code Playgroud)
哪个输出:
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:5
|
2 | let x = 5;
| -
| |
| first assignment to `x`
| help: make this binding mutable: `mut x`
3 | println!("The value of x is {}", x);
4 | x = …Run Code Online (Sandbox Code Playgroud) 当我可以进行可变变量绑定时,为什么还需要重新绑定/阴影?考虑:
let x = a();
let x = b(x);
Run Code Online (Sandbox Code Playgroud)
与
let mut x = a();
x = b(x);
Run Code Online (Sandbox Code Playgroud)
可变变量绑定允许对此变量进行可变借用.但是,影子比可变绑定有一些优势吗?
据我所知,编译器会在范围结束时自动生成代码以调用析构函数以在不再需要时删除对象.
在某些情况下,一旦不再需要删除对象,而不是等待它超出范围,这是有益的.是否可以在Rust中显式调用对象的析构函数?
根据Rust的书,"当一个绑定超出范围时,它们被绑定的资源被释放".这也适用于阴影吗?
例:
fn foo() {
let v = vec![1, 2, 3];
// ... Some stuff
let v = vec![4, 5, 6]; // Is the above vector freed here?
// ... More stuff
} // Or here?
Run Code Online (Sandbox Code Playgroud)