What is the error "error[E0716]: temporary value dropped while borrowed"?

How can I solve this problem efficiently?
error[E0716]: temporary value dropped while borrowed

let sc = (2,3);
let (s, c )= sc;
num[s] = &c.to_string();
1 Like

c.to_string() is not bound to any variable, hence its scope/lifetime ends once its immediately enclosing statement (in your case, the 3rd line) is over. Thus, it doesn't make sense to store a reference to it anywhere – that reference will immediately be a dangling pointer.

You should just store the generated string itself, i.e. num[s] = c.to_string() (and change the type of num accordingly).

1 Like

I forgot to add the num info. I will send you all the code.

let mut num = Vec::new();
for _ in 0..n{
        num.push("0");
    }
let sc = (2,3);
let (s, c )= sc;
num[s] = &c.to_string();

Your num vector has the type Vec<&'a str>, since you push the string literal "0" n times in it. This means the vector doesn't own the values it stores, since the values are references. For the code to work, you would have to change something:

let mut num = Vec::new();
for _ in 0..n{
        num.push("0".to_string());
    }
let sc = (2,3);
let (s, c )= sc;
num[s] = c.to_string();

Now you will have a Vec<String> where the vector owns its contents.

1 Like

Yeah, this doesn't change the answer. You'd want to store Strings in the vector, not &strs.

4 Likes

If you need the vector to mix heap-allocated strings with built-in string literals that must never be deallocated, then it has to keep track of which are which. The type that does this is Cow<str>. Use Vec<Cow<str>> and "0".into() or Cow::Borrowed("0"), and Cow::Owned(c.to_string()).

Note that &str is not a string itself, but a type that lets you "view" string data stored elsewhere. For &str to exist, there must be some string elsewhere that it borrows from. In case of "0" that string is built-in into your executable. In all other cases, you're responsible for storing the string somewhere.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.