references and borrowing
This commit is contained in:
@@ -1,3 +1,59 @@
|
|||||||
fn main() {
|
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.
|
||||||
|
*/
|
||||||
|
Reference in New Issue
Block a user