Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions 3-borrow-checker/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Borrow Checker example – fixed

This small program demonstrates how Rust's borrow checker enforces lifetimes for references.

The original version tried to return a reference (`&String`) that pointed to `name2`, a value that went out of scope at the end of an inner block. The compiler rightfully rejected the code because such a reference would have been dangling.

The corrected version simply declares **both** strings in the same scope so that they live long enough for the returned reference to remain valid.

Run it with:

```bash
cd 3-borrow-checker
cargo run
```

You should see:

```
The bigger string is: Pranav
```

---

Key take-aways:

* A reference can never outlive the value it points to.
* Keep referenced values in a scope that is at least as long as the references you hand out.
13 changes: 7 additions & 6 deletions 3-borrow-checker/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
fn main() {
// Move both names into the same scope so they live long enough
let name1 = String::from("Pranav");
let bigger = {
let name2 = String::from("Tiago");
let bigger = bigger_string(&name1, &name2);
bigger;
};
println!("The bigger string is: {bigger}");
let name2 = String::from("Tiago");

let bigger = bigger_string(&name1, &name2);

println!("The bigger string is: {}", bigger);
}

// Returns a reference to the longer string slice
fn bigger_string<'a>(a: &'a String, b: &'a String) -> &'a String {
if a.len() > b.len() {
a
Expand Down