From 8aee19c88d0361660ce68b0075823f71228d1fc0 Mon Sep 17 00:00:00 2001 From: Amoelle Date: Tue, 1 Jul 2025 17:14:12 +0300 Subject: [PATCH] references and borrowing --- references_and_borrowing/src/main.rs | 58 +++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/references_and_borrowing/src/main.rs b/references_and_borrowing/src/main.rs index e7a11a9..75cebfc 100644 --- a/references_and_borrowing/src/main.rs +++ b/references_and_borrowing/src/main.rs @@ -1,3 +1,59 @@ fn main() { - println!("Hello, world!"); + let mut string = String::from("forsen"); + + let len = calculate_length(&string); + println!("The length of string {string} is {len}"); + + add_string(&mut string); + + //let r1 = &mut string; + //let r2 = &mut string; + //println!("{} {}", r1, r2); + // this won't work because we can't borrow string more than once at a time + + let r1 = &mut string; + println!("{r1}"); + let r2 = &mut string; + println!("{r2}"); + // but we can borrow again once we use our variable + + // We also cannot have a mutable reference while we have an immutable one to the same value + // let r1 = &s; // no problem + // let r2 = &s; // no problem + // let r3 = &mut s; // BIG PROBLEM + // println!("{}, {}, and {}", r1, r2, r3); + + let r3 = &string; // not a problem + let r4 = &string; // we can + println!("{r3} and {r4}"); + // Variables r1 and r2 will not be used after this point. + + let r5 = &mut string; + println!("{r5}"); + + // let reference_to_nothing = dangle(); + let _reference_to_something = no_dangle(); } + +fn calculate_length(s: &String) -> usize { + s.len() +} + +fn add_string(s1: &mut String) { + s1.push_str(" is bald"); // borrowing wouldn't work here if we didn't make our string mutable +} + +//fn dangle() -> &String { // dangle returns a reference to a String +// let s = String::from("string"); // s is a new String +// +// &s // we return a reference to the String, s +//} // Here, s goes out of scope, and is dropped, so its memory goes away. + +fn no_dangle() -> String { + String::from("string") +} + +/* + At any given time, you can have either one mutable reference or any number of immutable references. + References must always be valid. +*/