与借阅检查员搏斗

时间:2015-07-01 05:55:52

标签: rust

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

1) check python 3 path in your system by using -> which python3
output will be like this  ->  /usr/bin/python3
2) then create a virtual environment-> virtualenv -p /usr/bin/python3 project
it will create a virtual environment name as project
3)to activate it run- > . project/bin/activate

我得到的编译器错误:

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>>>,
}

我已经纠结于所有的参考和削减,以及&和我的,我不知道如何离开。我哪里错了?

2 个答案:

答案 0 :(得分:5)

你有两个问题:

  • 无法摆脱借来的背景:请参阅Cannot move out of borrowed content when borrowing a generic type获取解释。

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

答案 1 :(得分:3)

因为你是Rust的新手,所以看看我怎么写它可能会有所帮助:

struct Node<T> {
    value: T,
    left: Option<Box<Node<T>>>,
    right: Option<Box<Node<T>>>,
}

impl<T> Node<T> {
    fn new(x: T) -> Node<T> {
        Node { value: x, left: None, right: None }
    }
    fn boxed(x: T) -> Box<Node<T>> {
        Box::new(Node::new(x))
    }
}

fn insert<T: PartialOrd>(root: &mut Option<Box<Node<T>>>, new: Box<Node<T>>) {
    if let Some(ref mut rbx) = *root {
        if new.value < rbx.value {
            insert(&mut rbx.left, new);
        } else {
            insert(&mut rbx.right, new);
        }
    } else {
        *root = Some(new);
    }
}

fn main() {
    let data = vec![6,1,2,3,4,5];
    let mut root = None;
    for val in data {
        insert(&mut root, Node::boxed(val));
    }
    println!("Root value: {}", root.unwrap().value); 
}

我意识到这不仅仅是一种练习,但请记住,这种数据结构不应超出某个树深度,否则可能会导致堆栈在递归解除分配时溢出。