如何使用Rust构建递归数据结构并对其进行操作?

问题描述 投票:0回答:1

从头到尾阅读https://doc.rust-lang.org/book/(2018年版)后,我开始进行练习的几个小型学习项目之一。

想法是重新创建我已经用Java编写的ID生成器。基于此的递归结构具有节点,每个节点包含一个字符列表,一个指向列表中当前字符的索引和一个子级(如果已设置)。这样,我想创建任何可用的字符组合(给定的字符列表等)。

在实现添加另一个节点的功能的中间,我的代码会产生几种不同的编译器错误,这取决于我尝试的实现类型。有时它们是矛盾的,而我无法理解编译器在问我什么。

在StackOverflow上搜索,我找到了几个示例,但据我所知,这些示例都不适合我所缺乏的知识。最后,我尝试以一个有效的示例https://stevedonovan.github.io/rust-gentle-intro/2-structs-enums-lifetimes.html#structs-with-dynamic-data使其适应我的需要,但再次失败,无法将节点插入节点。

以下是我的原始代码库:

main.rs

use idgen::FigureElement;

fn main() {

    let array = ['a', 'b', 'c'];

    //~ let fe = FigureElement {figure: Figure::Absence, index: 23};
    let mut fe2 = FigureElement::new(&array);
    let mut fe3 = FigureElement::new(&array);

    fe2.add_figure(fe3);

}

lib.rs


pub enum Figure<'a> {
    Position(Box<&'a mut FigureElement<'a>>),
    Absence,
}

pub struct FigureElement<'a> {

    figure: Figure<'a>,

    //~ values: Vec<char>,
    array: &'a [char],

    index: usize,

}

impl<'a> FigureElement<'a> {

    pub fn new(a: &'a [char]) -> FigureElement<'a> {

        FigureElement {
            figure: Figure::Absence,
            array: a,
            index: 0
        }

    }

    pub fn get_index(&self) -> usize {
        self.index
    }

    pub fn add_figure(&mut self, f: &'a mut FigureElement<'a>){

        println!("in add_figure");

        match &self.figure {

            Figure::Position(b) => {
                println!("in add_figure : position");
                    //~ let fe = b;
                    //~ fe.add_figure(f);
                    //~ *b.add_figure(f);
                    //~ let Figure::Position(fe) = &self.figure;
                    //~ fe.add_figure(f);
                    //~ b = &self.figure(fer);
                    //~ b.add_figure(f);
                    //~ fer.add_figure(f);
                    let fe = &*b;
                    fe.add_figure(f);
                },

            Figure::Absence => {

                println!("in add_figure : absence");
                self.figure = Figure::Position(Box::new(f));
                },

        }

    }

    pub fn get_value(&self) -> String {


        let s = match &self.figure {

            Figure::Position(..) => {
                let mut s = self.array[self.index].to_string();
                s.push_str(&self.get_value());
                s
                },

            Figure::Absence => self.array[self.index].to_string(),

        };

        s
    }

}

生命周期是根据编译器错误消息插入的。树结构不是预期的。编译器(?)版本为1.41.0。

rust recursive-datastructures
1个回答
0
投票

@@ Sean:您的更正做到了,我接受了它们作为对我问题的回答。

© www.soinside.com 2019 - 2024. All rights reserved.