我有一个带字段的结构:
struct A {
field: SomeType,
}
Run Code Online (Sandbox Code Playgroud)
给定a &mut A,如何移动值field并交换新值?
fn foo(a: &mut A) {
let mut my_local_var = a.field;
a.field = SomeType::new();
// ...
// do things with my_local_var
// some operations may modify the NEW field's value as well.
}
Run Code Online (Sandbox Code Playgroud)
最终目标相当于一项get_and_set()行动.在这种情况下,我并不担心并发性.
我想收集结构的更改并立即应用它们.基本大纲如下所示:
enum SomeEnum {
Foo,
Bar,
}
struct SomeStruct {
attrib: SomeEnum,
next_attrib: Option<SomeEnum>,
}
impl SomeStruct {
pub fn apply_changes(&mut self) {
if let Some(se) = self.next_attrib {
self.attrib = se;
}
self.next_attrib = None;
}
}
Run Code Online (Sandbox Code Playgroud)
这会产生以下编译器错误:
Run Code Online (Sandbox Code Playgroud)error[E0507]: cannot move out of borrowed content --> src/lib.rs:13:27 | 13 | if let Some(se) = self.next_attrib { | -- ^^^^ cannot move out of borrowed content | | | hint: to prevent move, use `ref se` or `ref mut se` …
我在尝试此代码时遇到错误,该代码实现了一个简单的链表。
use std::rc::Rc;
use std::cell::RefCell;
struct Node {
a : Option<Rc<RefCell<Node>>>,
value: i32
}
impl Node {
fn new(value: i32) -> Rc<RefCell<Node>> {
let node = Node {
a: None,
value: value
};
Rc::new(RefCell::new(node))
}
}
fn main() {
let first = Node::new(0);
let mut t = first.clone();
for i in 1 .. 10_000
{
if t.borrow().a.is_none() {
t.borrow_mut().a = Some(Node::new(i));
}
if t.borrow().a.is_some() {
t = t.borrow().a.as_ref().unwrap().clone();
}
}
println!("Done!");
}
Run Code Online (Sandbox Code Playgroud)
为什么会发生?这是否意味着Rust不如定位的安全?
UPD:如果添加此方法,则程序不会崩溃。
impl Drop for Node {
fn …Run Code Online (Sandbox Code Playgroud)