Rust 语言:不可变借用和可变借用错误(2 种情况)

时间:2021-05-27 07:40:19

标签: rust

我正在学习 Rust 并且正在研究学习中的编译器错误。但是,我有一个可变和不可变借用的情况,在第一种情况下没有错误,但在第二种情况下却出现错误,只需取消对 println 的注释。 我认为两者都会出错

案例 1(运行):

fn main() {
let mut s = String::from("Hello");

// does xyz below have a immutable reference to s?
let xyz = replace_one(&mut s);

// if xyz has a immutable reference to s, then how does pol work?
let pol = &mut s;

pol.replace_range(0.., "changed value");
println!("pol is {}", pol);

// by uncommenting this in the second case, I get an error, of immutable and mutable borrow.
// println!("{}",xyz); 

}

fn replace_one(data: &mut String) -> &String {
    data.replace_range(0.., "Howdy.");
    data
}

我在此假设 xyz 具有对 s 的不可变引用。没有函数或宏消耗 xyz,因此,鉴于它们在同一范围内,pol 不应该工作(?)。现在,在第二种情况下,我取消了 println 语句的注释,它会抛出一个错误。

情况 2(这不是):

fn main() {
    let mut s = String::from("Hello");


let xyz = replace_one(&mut s);


let pol = &mut s;

pol.replace_range(0.., "changed value");
println!("pol is {}", pol);

//  uncommenting this, throws an error showing that I have a immutable borrow at xyz 
// and a mutable borrow at pol.
    println!("{}",xyz);

}

fn replace_one(data: &mut String) -> &String {
    data.replace_range(0.., "Howdy.");
    data
}

我是生锈的新手。如果您能指导我找到有关这方面的任何资源,将会很有帮助。

0 个答案:

没有答案