Is there an operation for Rc or Arc which clones the underlying value and returns it to the caller?
我正在寻找大致类似于
1 2 3 4 5 6 | impl<T: Clone> for Arc< T > { fn take(mut self) -> T { Arc::make_mut(&mut self); Arc::try_unwrap(self).unwrap() } } |
换句话说,我想要
我们可以使用
1 2 3 4 5 6 7 8 9 10 11 12 | use std::rc::Rc; fn main() { let rc = Rc::new("Hello".to_string()); let mut cloned = (*rc).clone(); cloned.truncate(4); // verify that it's modified println!("{:?}", cloned); //"Hell" // verify that the original was not println!("{:?}", rc); //"Hello" } |
在某些情况下,Rust允许您省略
我们还可以通过使用适当的类型显式调用Rust来告诉Rust想要哪个
1 2 3 4 5 6 7 8 9 10 11 12 | use std::rc::Rc; fn main() { let rc3 = Rc::new(Rc::new(Rc::new("Hello".to_string()))); let mut cloned = String::clone(&rc3); cloned.truncate(4); // verify that it's modified println!("{:?}", cloned); //"Hell" // verify that the original was not println!("{:?}", rc3); //"Hello" } |