[Rust] About Reference and Lifetime

고승우·2024년 7월 10일
0

Rust

목록 보기
9/16

Reference

I wrote an article about the basic of Reference here

Borrowing References to Arbitrary Expressions

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?

  • Rust makes the anonymous variable live as long as the variable the let initialize.

Lifetime in Rust

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 Lifetime

static value lives for the program's entire execution. And rust calls it's life time as 'static lifetime

Reference and 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.

Struct Containing References

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 }
profile
٩( ᐛ )و 

0개의 댓글