Skip to content

Conversation

@melotik
Copy link
Owner

@melotik melotik commented Jun 23, 2025

What was wrong?

The example in 3-borrow-checker/src/main.rs failed to compile:

error[E0597]: `name2` does not live long enough
 --> src/main.rs:5:23
  |
5 |         let bigger = bigger_string(&name1, &name2);
  |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
8 |     };
  |     - `name2` dropped here while still borrowed
...
12 | }
  | - borrowed value needs to live until here

name2 was created in an inner block, but a reference to it escaped that block via the return value of bigger_string, leaving us with a dangling reference.

Fix implemented

  1. Move both name1 and name2 into the same (outer) scope so their lifetimes cover the returned reference.
  2. Remove the unnecessary inner block and simplify the bigger assignment.
  3. Added a small README in the example folder explaining the issue, the fix and the key take-aways.

The program now compiles and runs:

$ cargo run -q
The bigger string is: Pranav

Note: No public API changes, so the fix is confined to the example code only.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants