this post was submitted on 13 Mar 2024
10 points (100.0% liked)

Rust

6117 readers
10 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

[email protected]

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 2 years ago
MODERATORS
 

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
[–] [email protected] 14 points 9 months ago (2 children)

If you put an underscore as the first character in the variable name, that tells the compiler that the variable may go unused and you're okay with that. E.g.

let mut _last = &mut first;
[–] [email protected] 3 points 9 months ago* (last edited 9 months ago)

The issue is related to the binding being reassigned then never used. It's happening because they're using code generation where the final loop doesn't need to assign. (but previous loops use the assignment at the loop start. Just throwing all that in a function and adding the warning suppression fixes it.

edit: I'm wrong, using an underscore works

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

[–] [email protected] 3 points 9 months ago

That's a neat trick!

I knew it worked for params, but never thought to use it for variables.