007 通过链表学Rust之支持泛型

Rust
342
0
0
2022-04-30

介绍

视频地址:www.bilibili.com/video/av78062009/

相关源码:github.com/anonymousGiga/Rust-link...

详细内容

本节我们让我们的链表支持泛型。首先修改我们的定义如下:

pub struct List<T> {
    head: Link<T>,
}

type Link<T> = Option<Box<Node<T>>>;

struct Node<T> {
    elem: T, 
    next: Link<T>,
}

整体的实现代码如下:

pub struct List<T> {
    head: Link<T>,
}

type Link<T> = Option<Box<Node<T>>>;

struct Node<T> {
    elem: T,
    next: Link<T>,
}

impl<T> List<T> {
    pub fn new() -> Self {
        List { head: None }}

    pub fn push(&mut self, elem: T) {let node = Box::new(Node {
            elem: elem,
            next: self.head.take(),});
        self.head = Some(node);}

    pub fn pop(&mut self) -> Option<T> {
        self.head.take().map(|node| {
            self.head = node.next;
            node.elem
        })}
}

impl<T> Drop for List<T> {
    fn drop(&mut self) {let mut link = self.head.take();while let Some(mut node) = link {
            link = node.next.take();}}
}

#[cfg(test)]
mod tests {
    use super::List;

    #[test] 
    fn basics() {let mut list = List::new();
        assert_eq!(list.pop(), None);

        list.push(1);
        list.push(2);
        list.push(3);

        assert_eq!(list.pop(), Some(3));
        assert_eq!(list.pop(), Some(2));

        list.push(4);
        list.push(5);

        assert_eq!(list.pop(), Some(5));
        assert_eq!(list.pop(), Some(4));

        assert_eq!(list.pop(), Some(1));
        assert_eq!(list.pop(), None);}
}