关于 Rust 的所有权

杰威

我有一个关于 Rust 所有权的问题。

我没有使用过 Rust,但我知道 Rust 有一个所有权概念,并且 Rust 按所有权管理内存。我了解到 Rust 可以防止在编译时访问无效内存。

如果有如下代码

let s1 = String::from("hello");
let s2 = s1;

println!("{}, world!", s1);

它可能会显示错误,因为 s1 是无效内存。

在这里,我想知道以下情况下的结果。

let s1 = String::from("hello");
if(The condition that can't know in compile time)
   let s2 = s1;

println!("{}, world!", s1);

if 条件可以是 rand 或来自用户的输入等。

if 执行 if 语句 s1 将移动到 s2 并在 if 语句结束时删除。在这种情况下,访问 println 上的 s1 将产生错误。

但如果不执行 if 语句,则访问 s1 是有效的。在这种情况下,Rust 是如何运作的?

谢谢阅读。

kmdreko

病情影响不大。由于if may move s1,编译器必须考虑它为作用域的其余部分而移动。

操场上

fn main() {
    let s1 = String::from("hello");
    if std::env::args().next() == None { // runtime check
       let _s2 = s1;
    }
    
    println!("{}, world!", s1);
}
error[E0382]: borrow of moved value: `s1`
  --> src/lib.rs:10:28
   |
5  |     let s1 = String::from("hello");
   |         -- move occurs because `s1` has type `std::string::String`, which does not implement the `Copy` trait
6  |     if std::env::args().next() == None {
7  |        let _s2 = s1;
   |                  -- value moved here
...
10 |     println!("{}, world!", s1);
   |                            ^^ value borrowed here after move

如果您需要一个可能已移出的值,请使用Option.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章