Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

rust引用问题?

fn main() {
    let mut x = String::from("hi");
    let b=push(&mut x);//1
    println!("{}",x);//2
    println!("The value of x is: {}--",b);//3
}
fn push(s:&mut String)->&String{
    s.push_str("tt");
    return s
}

编译器报错提示很清楚,但是不太理解:"cannot borrow x as immutable because it is also borrowed as mutable",
2处提示"immutable borrow occurs here",这里打印x并没有加&,为什么会提示borrow,在1处虽然是可变引用,但是终归还是引用,所以x并没有被借走,还应该能打印,该去怎样理解这里的错误?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

因为你标记3的那里还在使用b,导致mutable borrow的作用域是你标记的1 2 3三行,在此期间,你不能再次有任何borrow行为了。

至于你不理解的地方,官方描述就是操作你借走的资源。
A ‘mutable reference’ allows you to mutate the resource you’re borrowing.
https://doc.rust-lang.org/1.8...

其实很好理解,如果引用不算borrow的话,那么rust真个borrow机制就不可能工作了。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...