I wrote an article about the basic of Reference
here
fn factorial(n: usize) -> usize { (1..n+1).product()
}
let r = &factorial(6);
// Arithmetic operators can see through one level of references.
assert_eq!(r + &1009, 1729);
Why value from factorial
func didn't drop?
let
initialize.Lifetime
is some stretch of program for which a reference could be safe to use. Lifetimes are entirely figments of Rust’s compile-time imagination. At run time, a reference is nothing but an address; its lifetime is part of its type and has no run-time representation.
static value lives for the program's entire execution. And rust calls it's life time as
'static lifetime
{
let r;
{
let x = 1;
r = &x; // `x` does not live long enough
}
assert_eq!(*r, 1);
}
In this example, referece's lifetime doesn't contain or enclose the variable's.
Suppose you’ve defined a structure containing two references like this
struct S<'a>
{
x: &'a i32,
y: &'a i32
}
let x = 10; let r;
{
let y = 20; {
let s = S { x: &x, y: &y };
r = s.x; }
}
println!("{}", r);
This code doesn’t create any dangling pointers. If you try to compile this, however, Rust will complain that y does not live long enough, even though it clearly does. The problem arises because both references in S
have the same lifetime 'a
.
Changing the definition of S to let each reference have a distinct lifetime fixes everything.
struct S<'a, 'b> { x: &'a i32,
y: &'b i32 }