Allow to refer to the value without the change in the ownership -> reference borrows the value
References are immutable by default unless mut is used
Reference is guaranteed to point to a valid value of a particular type for the life of that reference
fn main() {
let s1 = String::from("hello");
// due to reference s1 will not be dropped after the function call
let len = calculate_length(&s1);
println!("The length of '{s1}' is {len}.");
}
// we can pass a reference to a function as a parameter, String ownership is not transferred
fn calculate_length(s: &String) -> usize {
s.len()
}
fn main() {
// will return error as there is no value to borrow from
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}