008 通过链表学习Rust之实现Peek函数

Rust
324
0
0
2022-04-30

介绍

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

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

详细内容

在之前的链表实现中,我们没有实现获取表头元素的peek方法,本节尝试去实现它。

peek

根据我们之前学习的知识,可以快速的写出代码如下:

    pub fn peek(&self) -> Option<&T> {
        self.head.map(|node| {&node.elem
        })}

当我们运行时发现报错,原因是因为:node的生命周期不够长。此时的解决办法就是使用Option的as_ref,修改后的代码如下:

    pub fn peek(&self) -> Option<&T> {//self.head.map(|node| { 
        self.head.as_ref().map(|node| {&node.elem
        })}

peek_mut

同样的,我们还可以实现peek_mut函数。代码如下:

    pub fn peek_mut(&mut self) -> Option<&mut T> {
        self.head.as_mut().map(|node| {&mut node.elem
        })}

完整代码与测试

下面我们写出完整代码和测试代码:

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
        })}

    pub fn peek(&self) -> Option<&T> {//self.head.map(|node| { 
        self.head.as_ref().map(|node| {&node.elem
        })}

    pub fn peek_mut(&mut self) -> Option<&mut T> {
        self.head.as_mut().map(|node| {&mut node.elem
        })}
}

#[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);}

    #[test] 
    fn peek() {let mut list = List::new();
        assert_eq!(list.peek(), None);
        assert_eq!(list.peek_mut(), None);
        list.push(1); 
        list.push(2); 
        list.push(3);

        assert_eq!(list.peek(), Some(&3));
        assert_eq!(list.peek_mut(), Some(&mut 3));

        //list.peek_mut().map(|&mut value| {
        list.peek_mut().map(|value| { //取指针//value = 32*value = 32});

        assert_eq!(list.peek(), Some(&32));
        assert_eq!(list.pop(), Some(32));}
}