与借阅检查员搏斗

deg*_*egs 3 rust

我是Rust的新手.作为一个学习练习,我正在尝试制作一个基本的二叉树.这是我到目前为止:

fn main() {
    let data = vec![6,1,2,3,4,5];

    let mut root = Node::<i32> { value: data[0], left: None, right: None };

    for val in data {
        createAndInsert::<i32>(&root, val);
    }
    println!("Root value: {}", root.value); 
}

fn createAndInsert<T: PartialOrd>(mut root: &Node<T>, value: T) {
    let mut n = Node::<T> { value: value, left: None, right: None };
    insert::<T>(&root, &n);
}

fn insert<T: PartialOrd>(mut curr: &Node<T>, new: &Node<T>) {
    if new.value > curr.value {
        match curr.right {
            Some(ref n) => insert(n, new),
            None => curr.right = Some(Box::new(*new))
        }
    } else {
        match curr.left {
            Some(ref n) => insert(n, new),
            None => curr.left = Some(Box::new(*new))
        }
    }
}

struct Node<T: PartialOrd> {
    value: T,
    left: Option<Box<Node<T>>>,
    right: Option<Box<Node<T>>>,
}
Run Code Online (Sandbox Code Playgroud)

我得到的编译器错误:

test.rs:21:48: 21:52 error: cannot move out of borrowed content
test.rs:21             None => curr.right = Some(Box::new(*new))
                                                          ^~~~
test.rs:26:47: 26:51 error: cannot move out of borrowed content
test.rs:26             None => curr.left = Some(Box::new(*new))
                                                         ^~~~
test.rs:21:21: 21:54 error: cannot assign to immutable field `curr.right`
test.rs:21             None => curr.right = Some(Box::new(*new))
                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.rs:26:21: 26:53 error: cannot assign to immutable field `curr.left`
test.rs:26             None => curr.left = Some(Box::new(*new))
                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to 4 previous errors
Run Code Online (Sandbox Code Playgroud)

我已经把自己纠结在所有的参考和削减和&和s和我的,我不知道如何离开.我哪里错了?

Chr*_*gan 5

你有两个问题:

  • 无法摆脱借用的上下文:请参阅借用泛型类型进行解释时,不能移出借来的内容.

  • 无法分配到不可变字段:您只有一个&Node<T>; 修改Node你需要一个&mut Node<T>.mut curr在模式中只是使绑定变为可变,这意味着您可以为其分配新值curr.但是,您不能修改所curr引用的内容.传播&至- &mut整个代码转换,它会工作.