rust-unofficial / too-many-lists

Learn Rust by writing Entirely Too Many linked lists
https://rust-unofficial.github.io/too-many-lists/
MIT License
3.16k stars 276 forks source link

in rust edition 2021, fourth-peek test code shows `list` does not live long enough #286

Open dev-m1-macbook opened 10 months ago

dev-m1-macbook commented 10 months ago

the following code errors with list does not live long enough error in rust 2021 edition

#[test]
fn peek() {
    let mut list = List::new();
    assert!(list.peek_front().is_none());
    list.push_front(1); list.push_front(2); list.push_front(3);

    assert_eq!(&*list.peek_front().unwrap(), &3);
    //                       --> `list` does not live long enough (borrowed value does not live long enough)
}

but the following code works:

#[test]
fn peek() {
    let mut list = List::new();
    assert!(list.peek_front().is_none());
    list.push_front(1); list.push_front(2); list.push_front(3);

    // not a good name
    let elem: i32 = list.peek_front().unwrap();
    assert_eq!(elem, 3);
}
indirection42 commented 8 months ago

The snippet you posted would be ok. If you leave off the semicolon of the last expression, the compiler will complain.

aresbit commented 8 months ago

test test::peek ... ok

pobv commented 3 weeks ago

Shouldn't there be an additional *?

let elem: i32 = *list.peek_front().unwrap();

and do we really have to copy?