Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

rust - 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?

question from:https://stackoverflow.com/questions/65886376/temporary-value-dropped-while-borrowed-inside-if-else

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...