Ownership and moves

Because variables are in charge of freeing their own resources,
resources can only have one owner. This also prevents resources
from being freed more than once. Note that not all variables own
resources (e.g. references).

When doing assignments (let x = y) or passing function arguments by value
(foo(x)), the ownership of the resources is transferred. In Rust-speak,
this is known as a move.

After moving resources, the previous owner can no longer be used. This avoids
creating dangling pointers.

  1. // This function takes ownership of the heap allocated memory
  2. fn destroy_box(c: Box<i32>) {
  3. println!("Destroying a box that contains {}", c);
  4. // `c` is destroyed and the memory freed
  5. }
  6. fn main() {
  7. // _Stack_ allocated integer
  8. let x = 5u32;
  9. // *Copy* `x` into `y` - no resources are moved
  10. let y = x;
  11. // Both values can be independently used
  12. println!("x is {}, and y is {}", x, y);
  13. // `a` is a pointer to a _heap_ allocated integer
  14. let a = Box::new(5i32);
  15. println!("a contains: {}", a);
  16. // *Move* `a` into `b`
  17. let b = a;
  18. // The pointer address of `a` is copied (not the data) into `b`.
  19. // Both are now pointers to the same heap allocated data, but
  20. // `b` now owns it.
  21. // Error! `a` can no longer access the data, because it no longer owns the
  22. // heap memory
  23. //println!("a contains: {}", a);
  24. // TODO ^ Try uncommenting this line
  25. // This function takes ownership of the heap allocated memory from `b`
  26. destroy_box(b);
  27. // Since the heap memory has been freed at this point, this action would
  28. // result in dereferencing freed memory, but it's forbidden by the compiler
  29. // Error! Same reason as the previous Error
  30. //println!("b contains: {}", b);
  31. // TODO ^ Try uncommenting this line
  32. }