Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...