rust - 为什么打开克隆的 Rc 会引起 panic ?

标签 rust reference-counting panic

为什么这段代码会在第 7 行出现 panic ? foo_unwrapped 不应该是第 5 行的 Some(3) 而不是 None 吗?

use std::rc::Rc;
fn main()
{
    let foo: Rc<i32> = Rc::new(3);
    let mut foo_cloned = Rc::clone(&foo);
    let mut foo_unwrapped = Rc::get_mut(&mut foo_cloned).unwrap();  
    foo_unwrapped = &mut 42;
}

最佳答案

来自 the Rc docs (强调我的)

pub fn get_mut(this: &mut Rc<T>) -> Option<&mut T>

Returns a mutable reference into the given Rc, if there are no other Rc or Weak pointers to the same allocation.

Returns None otherwise, because it is not safe to mutate a shared value.

See also make_mut, which will clone the inner value when there are other pointers.


你有两个 Rc指向相同数据的指针(即 foofoo_cloned ),因此获取对数据的可变引用是不安全的。Rc不是摆脱 Rust 借用语义的魔术。 Rust 仍然是一种单一所有权语言,并且仍然强制执行所有相同的保护;只是在 Rc 的情况下,强制发生在运行时而不是编译时。

关于rust - 为什么打开克隆的 Rc 会引起 panic ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67865411/

相关文章:

macos - Rust、OpenSSL、solana-test-validator 库未加载问题

objective-c - 引用计数等于 0 的对象仍然是持久的

c++ - 原子 decref 实现之间的区别

go - 我可以从 panic 中恢复过来,处理错误,然后再次 panic 并保留原始堆栈跟踪吗?

c++ - 创建链接到 Rust dylib 的共享 C 对象以在 R 中使用

operating-system - Cargo.toml 操作系统对 Crate 的依赖

rust - 如何使用前缀键搜索获得排序的键值映射?

swift - Swift 中 ARC 溢出的可能性?

linux - 内核崩溃后系统是否有可能保持事件状态?

rust - 将 panic 重定向到指定的缓冲区