Timmmm
Timmmm

Reputation: 96547

Temporary value dropped while borrowed inside if else

I'm using Rusqlite which lets you do queries like this:

statement.query_row(params!([1, 2, 3]), ...);

params!() is defined like this:

macro_rules! params {
    () => {
        $crate::NO_PARAMS
    };
    ($($param:expr),+ $(,)?) => {
        &[$(&$param as &dyn $crate::ToSql),+] as &[&dyn $crate::ToSql]
    };
}

This works fine but in some cases I would like to do something like this:

statement.query_row(if x { params![1, 2, 3] } else { params![4, 5] }, ...

Unfortunately it does not work - you get a temporary value dropped while borrowed error. I simplified the problem to this (playground):

fn main() {
    foo(&[&1, &2, &3]); // Fine!

    let x = 1;
    let y = true;
    
    let a = if y {
        &[&x, &2, &3]
    } else {
        &[&5, &6, &7]
    };
    
    foo(a); // Error
}

fn foo(_x: &[&i32]) {
}

This makes sense but it's quite annoying. My current workaround is basically this:

let params_a = params![1, 2, 3];
let params_b = params![4, 5];
statement.query_row(if x { params_a } else { params_b }, ...

But it kind of sucks. Is there a better way?

Upvotes: 2

Views: 267

Answers (1)

Peter Hall
Peter Hall

Reputation: 58695

It's pretty common in Rust to need to create a new binding in order to extend the lifetime of a temporary. Your solution is probably the best way to do it.

The creators of the rusqlite crate obviously didn't anticipate this kind of usage - and they haven't made it easy. You could create your own macro that boxed the values instead of returning references, but it doesn't really seem worthwhile.

You could also just move the call to statement.query_row into the conditional blocks:

if x {
    statement.query_row(params![1, 2, 3]); 
} else {
    statement.query_row(params![4, 5]);
}

which would avoid creating parameter objects that you don't need.

Upvotes: 3

Related Questions