How to fix "unused borrow" warning?

The following rust script will trigger "unused borrow" warning.

"warning: unused borrow that must be used
label: the borrow produces a value"

How to avoid it?

Thank in advance for any help

Eli

macro_rules! v_append{
    ($v:expr, $($args:expr),*) => {
        $(
            $v.push($args);
        )*
        $v
    }
}

fn main() {
    let mut v = Vec::<i64>::new();
    v_append!(&mut v, 1, 2, 3);
    println!("{:#?}", &v);
}

After the macro expansion this code becomes this.

fn main() {
    let mut v = Vec::<i64>::new();
    (&mut v).push(1);
    (&mut v).push(2);
    (&mut v).push(3);
    &mut v;
    println!("{:#?}", &v);
}

Indeed that &mut v line looks suspicious, hence the warning. If you really don't care and just want to throw away the warning anyway, you can replace the $v line with #[allow(unused_must_use)] {v} which does so. Note that this extra {} may change the lifetime of the value, but it's ok for this specific case with references.

Also, you don't need the macro for this specific code.

fn main() {
    let mut v = Vec::<i64>::new();
    v.extend([1, 2, 3]);
    println!("{:#?}", &v);
}
1 Like