打印树 - 尝试访问字段,但未找到具有该名称的字段

时间:2015-05-18 14:31:51

标签: rust imperative-programming imperative-languages

我正在尝试编写我的第一个Rust程序。我想在屏幕上打印一个简单的树,但我无法访问value属性,它说

  

错误1尝试访问类型value上的字段Node,但没有字段   用这个名字找到了c:\ users \ zhukovskiy \ documents \ visual studio   2013 \ Projects \ rust_application1 \ rust_application1 \ src \ main.rs 21 20 rust_application1

use std::io;

enum Node {
    Branch { value: i32, next: *const Node },
    Leaf { value: i32 }
}

fn main() {
    let leaf = Node::Leaf { value: 15 };
    let branch = Node::Branch { value: 10, next: &leaf };
    let root = Node::Branch { value: 50, next: &branch };

    let current = root;
    loop {
        match current {
            Node::Branch => { println!("{}", current.value); current = current.next; },
            Node::Leaf => { println!("{}", current.value); break; }, 
        }
    }
}

3 个答案:

答案 0 :(得分:4)

仅因为Node的两个变体都有value字段,并不意味着您可以直接访问它。您可以通过匹配值(这些是等效的)来获得它:

let value = match leaf {
    Node::Branch { value, .. } => value,
    Node::Leaf { value } => value,
};

let value = match leaf {
    Node::Branch { value, .. } | Node::Leaf { value } => value,
};

但是如果你要做很多事情,你可能想要添加一个方法:

impl Node {
    pub fn get_value(&self) -> i32 {
        match self {
            &Node::Branch { value, .. } => value,
            &Node::Leaf { value } => value,
        }
    }
}

...然后您可以这样使用:

let value = leaf.get_value();

答案 1 :(得分:2)

由于您的所有枚举变体都具有相同的字段,因此您可以将字段提取到外部结构中,并仅保留枚举内不同的字段。这样您就可以直接访问内部value字段。如果您想了解自己的节点是Branch还是Leaf,则需要在kind字段上进行匹配。另外,我建议使用Rc<Node>而不是*const Node,因为访问*const Node指向的值需要不安全的代码,并且很可能会让您在更复杂的代码中遇到麻烦。

enum NodeKind {
    Branch(*const Node),
    Leaf,
}

use NodeKind::*;

struct Node {
    value: i32,
    kind: NodeKind,
}

fn main() {
    let leaf = Node{ value: 15, kind: Leaf };
    let branch = Node { value: 10, kind: Branch(&leaf) };
    let root = Node { value: 50, kind: Branch(&branch) };
}

我认为你真正想要的是以下代码:PlayPen

答案 2 :(得分:1)

利用我的直觉魔力,我猜你有一些像这样的代码:

enum Node {
    Branch { value: i32 },
    Leaf { value: i32 },
}

fn main() {
    let leaf = Node::Leaf { value: 15 };

    println!("{}", leaf.value);
}

确实有错误:

<anon>:9:20: 9:30 error: attempted access of field `value` on type `Node`, but no field with that name was found
<anon>:9     println!("{}", leaf.value);
                            ^~~~~~~~~~

问题是leaf的类型是Node,而Node有两种变体,BranchLeaf。没有名为Node::BranchNode::Leaf的类型。您需要匹配枚举以彻底处理所有情况:

enum Node {
    Branch { value: i32 },
    Leaf { value: i32 },
}

fn main() {
    let leaf = Node::Leaf { value: 15 };

    match leaf {
        Node::Branch { value } => println!("Branch [{}]", value),
        Node::Leaf { value }   => println!("Leaf [{}]", value),
    }
}