rust 中的可变所有权

问题描述 投票:0回答:1

我是新的 Rust 语言。我试图理解所有权和借用的概念。

    let mut s = String::from("hello");
    {
    s.push_str(" world");
    let mut r1 = &mut s;
    println!("{}",s);
    }
    let mut s = String::from("hello");
    {
    s.push_str(" world");
    let mut r1 = &mut s;
    println!("{}",r1);
    }

如果我执行代码,它没有显示任何错误。

但是如果我添加变量“r1”或“s”的另一条打印语句,则会显示错误。无法理解为什么显示错误

    let mut s = String::from("hello");
    {
    s.push_str(" world");
    let mut r1 = &mut s;
    println!("{}",s);
    println!("{}",r1);
    }

错误信息:

错误[E0502]:无法将

s
借用为不可变的,因为它也借用为可变的 --> /tmp/3uevECWJtw/main.rs:9:19 | 8 | 让 r1 = &mut s; | ------ 可变借用发生在这里 9 | println!("{}",s); | ^ 不可变借用发生在这里 10 | 10 println!("{}",r1); | -- 稍后在这里使用可变借用 | = 注意:此错误源自宏
$crate::format_args_nl
,它来自宏
println
的扩展(在 Nightly 构建中,使用 -Z 宏回溯运行以获取更多信息)

请帮助我理解这一点。

rust rust-cargo
1个回答
0
投票

直接来自铁锈书

Rust 强制执行类似的规则来组合可变和不可变引用。此代码会导致错误:

此代码无法编译!

    let mut s = String::from("hello");

    let r1 = &s; // no problem
    let r2 = &s; // no problem
    let r3 = &mut s; // BIG PROBLEM

    println!("{}, {}, and {}", r1, r2, r3);

错误如下:

$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
 --> src/main.rs:6:14
  |
4 |     let r1 = &s; // no problem
  |              -- immutable borrow occurs here
5 |     let r2 = &s; // no problem
6 |     let r3 = &mut s; // BIG PROBLEM
  |              ^^^^^^ mutable borrow occurs here
7 |
8 |     println!("{}, {}, and {}", r1, r2, r3);
  |                                -- immutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
© www.soinside.com 2019 - 2024. All rights reserved.