Rust error on dyn ToSql + Sync: Temporary which is freed while still in use

467 Views Asked by At

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.

1

There are 1 best solutions below

0
Kevin Reid On

You can extend the life of the values created within the if block by assigning them to (otherwise uninitialized) variables declared outside the block.

let addr: String;
let addr_ref: &str;
if name.is_some() {
    addr = "a".to_string();
    addr_ref = &addr;
    params.push(&addr_ref);
}

The variables keep the String alive 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 params inside the outer scope here. If you want to, say, return it from the function, you'll need Vec<Box<dyn ToSql + Sync>> instead. But if you don't, then this lets you continue using &dyn ToSql and avoid extra boxing.