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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…