Removing last will break my library.

#[macro_export]
macro_rules! list {
    () => {
	None
    };
    [ $x:expr, $( $y:expr ),* ] => {
	{
	    let mut first = cons($x, &None);
	    let mut last = &mut first;
	    $(
		let yet_another = cons($y, &None);
		if let Some(ref mut last_inner) = last {
		    let last_mut = Rc::get_mut(last_inner).unwrap();
		    last_mut.cdr = yet_another;
		    last = &mut last_mut.cdr;
		}
	    )*
	    first
	}
    }
}

This macro works as I expected because it can pass these tests.

    #[test]
    fn dolist() {
        let mut v = vec![];
        dolist!((i &cons(10, &list![20, 30, 40])) {
            v.push(i.car);
        });
        assert_eq!(v, vec![10, 20, 30, 40]);
    }

    #[test]
    fn turn_list_to_vec() {
        assert_eq!(list_to_vec(&list![1, 2, 3]), vec![1, 2, 3]);
    }

    #[test]
    fn count_elements() {
        assert_eq!(list_len(&list![10, 20, 30]), 3);
    }

However I got the warning "value assigned to last is never read."

How can I avoid this warning?

P.S. Full code

you are viewing a single comment's thread
view the rest of the comments
[–] 2 points 2 years ago* (last edited 2 years ago) (1 child)

I misunderstood the reason the error was showing up. It seems like using a closure fixes it though.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=247730dfc1fbeeb8e2263ea3b95d6c0a

#[macro_export]
macro_rules! list {
    () => {
        None
    };
    [ $x:expr, $( $y:expr ),* ] => {{
        #[allow(unused_assignments)]
        let closure = move || {
            let mut first = cons($x, &None);
            let mut last = &mut first;

            $(
                let yet_another = cons($y, &None);
                if let Some(ref mut last_inner) = last {
                    let last_mut = Rc::get_mut(last_inner).unwrap();
                    last_mut.cdr = yet_another;

                    last = &mut last_mut.cdr;
                }
            )*

            first
        };

        closure()
    }}
}
  • source
  • parent
  • hideshow 1 child comment