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

标签 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在这两种情况下都可变地借用了名称,而 push_str 也可变地借用了名称,那么为什么第一个示例编译?
如果我调用 say_hello()即使仍然有两个可变借用,为什么两者的顺序无关紧要?
编辑:
这是相似的吗?
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 的借用规则之一是 mutable references are exclusive .意思是,而 x还活着,name不能使用。
那么,为什么第一个示例即使 x 也能编译?还在范围内吗?因为 Rust 也有 non-lexical lifetimes含义 x在最后一次使用后停止“生活”。

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 - 为什么借用顺序在 rust 中很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62959393/

相关文章:

rust - 从函数返回 lazy_static Mutex 的 MutexGuard 需要生命周期参数

multithreading - 管理绿色线程

workflow - Rust 库开发工作流程

unit-testing - 在宏上下文测试中使用 panic::catch_unwind 以解决单元测试中的 panic 问题

rust - 如何在不使用 Box 的情况下从特征方法返回匿名类型?

webpack - rust/Wasm : Module not found: Error: Can't resolve 'env' in

linked-list - 在构建链表时如何保持对最后一个节点的可变引用?

rust - 如何在不运行的情况下构建 Rust 示例

rust - std::num::Primitive 发生了什么?

rust - 如何以功能方式从列表创建 map ?