error[E0716]: temporary value dropped while borrowed

Situation

You get a warning (IDE or Cargo) that tells you to consider using a let to fix your error… then you notice that the line in question is already using a let. What’s going on?

Recreating the Issue

First, let’s setup a simple situation that recreates the issue.

Loading some Fake Data

First, we’ll load some fake data.

fake-data.png

The contents of this function don’t matter so much; but make the sample easier to illustrate.

Initial main Function

So we write a main function to grab that data, unwrap it and just print out the first key/value pairs.

Note that we are using the nightly toolchain to enable the .first_key_value() function.

Here, we see our first confusing suggestion.

ide-1.png

It’s telling us to consider using a let on the line that is already using a let.

Initial cargo build

What does cargo tell us? Maybe it’s better?

cargo-1.png

Cargo is a bit more descriptive about why it is a problem. It seems the value is dropped at the end of the unwrap call. Further down though, we can see a confusing suggestion about the let. Well, let’s just try it.

Trying the suggested let binding

ide-2.png

As expected, delegating it to another variable does not actually impact the error. I am not sure why cargo and the IDE are suggesting it.

Fixing the Issue

If the cargo suggestion does not work, how do we fix it?

If we think about the fact that both cargo and the IDE both suggested introducing a let statement, we might see that it is still possible.

In this example, we make the function call on one line, then add an if let on the next line.

ide-3.png

By replacing the expect with if let, the error goes away.

The app will now run. Sometimes it will print the first key/value pair and sometimes, because of our chaos, it will say that it failed to load any data.


© 2019. All rights reserved.