为什么这段代码会在第 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 otherRc
orWeak
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
指向相同数据的指针(即 foo
和 foo_cloned
),因此获取对数据的可变引用是不安全的。Rc
不是摆脱 Rust 借用语义的魔术。 Rust 仍然是一种单一所有权语言,并且仍然强制执行所有相同的保护;只是在 Rc
的情况下,强制发生在运行时而不是编译时。
关于rust - 为什么打开克隆的 Rc 会引起 panic ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67865411/