I am working on a rust project that is using the following code
let mut container: Vec<&(dyn ToSql + Sync)> = Vec::new();
I have a variable name which is of type Option. I am getting this error when I execute the following snippet
if name.is_some()
{
let addr: &String = &"a".to_string();
params.push(&addr);
}
error[E0716]: temporary value dropped while borrowed | 56 | let addr: &String = &"a".to_string(); | ^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use 57 | container.push(&addr); 58 | }; | - temporary value is freed at the end of this statement
I am trying to figure out a way to extend the lifetime of the variable and fix this error keeping the structure intact.
You can extend the life of the values created within the
ifblock by assigning them to (otherwise uninitialized) variables declared outside the block.The variables keep the
Stringalive to the end of the outer scope, but are only used if the inner scope assigns to them.Note that this will only work assuming that you're going to use
paramsinside the outer scope here. If you want to, say, return it from the function, you'll needVec<Box<dyn ToSql + Sync>>instead. But if you don't, then this lets you continue using&dyn ToSqland avoid extra boxing.