gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:10:41 26 4
gpt4 key购买 nike

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

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

最佳答案

仅仅因为 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();

关于rust - 打印树 — 尝试访问字段,但未找到具有该名称的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30305974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com