为什么借用顺序在 Rust 中很重要?

编程入门 行业动态 更新时间:2024-10-12 05:47:53
本文介绍了为什么借用顺序在 Rust 中很重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 fn say_hello(s: &str) { println!("Hello {}", s); }

为什么这样做

fn main() { let mut name = String::from("Charlie"); let x = &mut name; say_hello(x); name.push_str(" Brown"); }

但这不是吗?

fn main() { let mut name = String::from("Charlie"); let x = &mut name; name.push_str(" Brown"); say_hello(x); }

我所做的只是切换了两个函数的顺序,但似乎 x 在这两种情况下都可变地借用了 name,而 push_str 也可变地借用了 name,那么为什么第一个示例编译?

all I did was switch the order of the two functions but it seems like x has mutably borrowed name and push_str has also mutably borrowed name in both situations, so why does the first example compile?

如果我去掉对 say_hello() 的调用,为什么即使仍然有两个可变借用,两者的顺序无关紧要?

If I take out the call to say_hello() why does the order of the two not matter even though there are still two mutable borrows?

这是相似的吗?

fn change_string(s: &mut String) { // s is mutably borrowed but isn't used yet println!("{}", s.is_empty()); // so the scopes don't overlap even though is_empty is making an immutable borrow? s.push_str(" Brown"); }

推荐答案

Rust 的借用规则之一是 可变引用是独占的.意思是,当 x 活着时,不能使用 name.

One of Rust's borrowing rules is that mutable references are exclusive. Meaning, while x is alive, name cannot be used.

那么,为什么即使 x 仍在作用域内,第一个示例仍能编译?因为 Rust 也有 non-词法生命周期 意味着 x 停止生活";上次使用后.

So, why does the first example compile even if x is still in scope? Because Rust also has non-lexical lifetimes meaning x stops "living" after its last use.

fn main() { let mut name = String::from("Charlie"); let x = &mut name; say_hello(x); // "x"s lifetime ends here, releasing the exclusive borrow name.push_str(" Brown"); // "name" can be used again }

更多推荐

为什么借用顺序在 Rust 中很重要?

本文发布于:2023-11-02 18:22:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1553090.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   中很   Rust

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!