1

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

错误 1 ​​尝试访问valuetype 上的字段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; }, 
        }
    }
}
4

3 回答 3

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();
于 2015-05-18T14:41:40.207 回答
2

由于所有枚举变量都具有相同的字段,因此您可以将字段提取到外部结构中,并且只保留枚举内部不同的字段。这样您就可以直接访问内部value字段。当您想知道您的节点是 aBranch还是 aLeaf时,您需要在kind字段上进行匹配。另外我建议使用 aRc<Node>而不是 a *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

于 2015-05-18T14:58:12.187 回答
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);
                            ^~~~~~~~~~

问题是 的类型leafNode,并且Node有两个变体,Branchor Leaf。没有称为Node::Branchor的类型Node::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),
    }
}
于 2015-05-18T14:43:16.020 回答