rustimperative-programmingimperative-languages

Printing a tree — attempted access of field, but no field with that name was found


I'm am trying to write my first Rust program. I want to print a simple tree on the screen, but I cannot access a value property, it says

Error 1 attempted access of field value on type Node, but no field with that name was found 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; }, 
        }
    }
}

Solution

  • Just because both variants of Node have a value field, doesn't mean you can access it directly. You can get it by matching on the value (these are equivalent):

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

    But if you're going to do this a lot, you probably want to add a method:

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

    ...which you can then use like so:

    let value = leaf.get_value();