< 返回我的博客

floydawong 发表于 2020-07-03 11:45

Tags:list, struct

https://doc.rust-lang.org/rust-by-example/custom_types/enum/testcase_linked_list.html

#[derive(Debug)]
struct List {
    head: Option<Box<List>>,
    num: i32,
}

impl List {
    fn new() -> List {
        List { head: None, num: 0 }
    }

    fn prepend(self, elem: i32) -> List {
        List {
            head: Some(Box::new(self)),
            num: elem,
        }
    }

    fn len(&self) -> u32 {
        match &self.head {
            Some(list) => list.len() + 1,
            None => 0,
        }
    }

    fn stringify(&self) -> String {
        match &self.head {
            Some(list) => format!("{}, {}", self.num, list.stringify()),
            None => format!("Nil"),
        }
    }
}

fn main() {
    let mut list = List::new();

    list = list.prepend(1);
    list = list.prepend(2);
    list = list.prepend(3);

    println!("linked list has length: {}", list.len());
    println!("{}", list.stringify());
}

评论区

写评论
haowqs 2020-12-03 14:13

里面用到的是递归吗

作者 floydawong 2020-10-20 17:17

多谢~

--
👇
rdigua: 加油

too-many-lists

rdigua 2020-10-09 11:47
1 共 3 条评论, 1 页