Implicit ownership within Rust

100 Views Asked by At

I expect the following code to not compile due to outliving but it works.

fn main() {
    let x;
    {
        let y = &13;
        x = y;
    }
    println!("{}", x); 
}
13

The same example with composite types raises an error as I wanted.

fn main() {
    let x: &Box<i32>; 
    {
        let y = &Box::new(13);
        x = y; 
    }
    println!("{}", x); 
}
error[E0716]: temporary value dropped while borrowed
 --> ./life_1_2.rs:4:18
  |
4 |         let y = &Box::new(13);
  |                  ^^^^^^^^^^^^ creates a temporary which is freed while still in use
5 |         x = y;
6 |     }
  |     - temporary value is freed at the end of this statement
7 |     println!("{}", x);
  |                    - borrow later used here
  |
  = note: consider using a `let` binding to create a longer lived value

A typical outliving example gives an error too:

fn main() { 
    let x;
    {
         let y = 13;
         x = &y; 
    }
    println!("{}", x); 
}
error[E0597]: `y` does not live long enough
 --> ./life_1.rs:5:13
  |
5 |         x = &y;
  |             ^^ borrowed value does not live long enough
6 |     }
  |     - `y` dropped here while still borrowed
7 |     println!("{}", x);
  |                    - borrow later used here

It seems like Rust automatically manages the assignment through ownership instead of borrowing when dealing with primitive types. Does anybody know if it is correct an in such case why? Unfortunately I did not find any answer.

0

There are 0 best solutions below