diff --git a/3-borrow-checker/README.md b/3-borrow-checker/README.md new file mode 100644 index 0000000..c3c91bb --- /dev/null +++ b/3-borrow-checker/README.md @@ -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. diff --git a/3-borrow-checker/src/main.rs b/3-borrow-checker/src/main.rs index 95260e5..c5aacdf 100644 --- a/3-borrow-checker/src/main.rs +++ b/3-borrow-checker/src/main.rs @@ -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