Analyze the following Rust code snippet. Does it have a lifetime-related error?

Go & Rust interview question for Advanced practice.

Answer

No, the code is correct because the variable result is never used.

Explanation

The code compiles successfully because the variable result is never actually used. The borrow checker can see that result is assigned a value but then goes out of scope without being read. If the println! line were uncommented, the code would fail to compile because result would be used after string2 (one of the values it could be referencing) has been dropped, which would be a use-after-free error. Since it's not used, there's no error.

Related Questions