rust - 可变字符串引用是否实现复制

标签 rust

<分区>

在下面的代码中,我希望编译器在 hello 函数自 mutable references do not implement Copy 以来的第二次调用时提示 use of moved value: xref。编译器不会引发任何此类错误。我在这里缺少什么?

fn main() {
    let mut x: String = "Developer".to_string();
    let x_ref: &mut String = &mut x;
    hello(x_ref);
    hello(x_ref);
}

fn hello(a: &mut String) {
    println!("Hello {}", a);
}

最佳答案

您的示例依次使用可变引用,这允许编译器执行 implicit reborrow .它基本上将这段代码变成了这样:

    hello(&mut *x_ref);
    hello(&mut *x_ref);

现在您有两个单独的可变借用,每个借用仅在函数调用的生命周期内发生,因此它们不会相互冲突。

如果您尝试同时使用它两次,您会看到一个错误。

fn main() {
    let mut x: String = "Developer".to_string();
    let x_ref: &mut String = &mut x;
    hello(x_ref, x_ref);
}

fn hello(a: &mut String, b: &mut String) {
    println!("Hello {} and {}", a, b);
}

关于rust - 可变字符串引用是否实现复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67304498/

相关文章:

macros - 宏中 `use` 的正确方法

rust - 如何将异步函数放入 Rust 中的映射中?

pointers - 是什么使得 Rust 中返回的引用字符串成为悬空指针?

rust - 递归探索多维向量

string - 有没有办法在 Rust 中为字符添加偏移量?

rust - Rust 项目中的工作区内依赖关系

rust - 了解 Diesel 中的特征边界误差

rust - 为什么有时 my_arc_mutex.clone() 在使用完之前会被释放?

unit-testing - 在 Rust 单元测试工具中,如何等待回调被调用?

rust - 如何重复循环由项目的属性确定的集合的子集?