Ownership in Rust

  • Automatically drops when it goes out of scope.
    • For nested structs, it drops from the parent to the child.
    • More precisely, it drops when the block scope of the ownership ends.
      • When the ownership is associated with something:
        • Variable declaration: let a = b
        • Passing the variable itself as an argument: f(a)
  • When passing a value (passing ownership) to a function, it gets dropped at the end of that function’s scope.
    • This can be surprising.
  • If you don’t want this behavior, instead of passing ownership, you can lend the borrowing rights.
    • Using &.
    • The type of the borrowing side’s argument is &Foo instead of Foo.
    • At this time, it feels like the memory holds the reference address to the original value.
    • Dereferencing:
      • When you want to obtain the value from the reference (&T to T), you use *.
      • There is also automatic dereferencing.
        • When performing simple arithmetic operations, it automatically converts &T to T.
          • Why?
          • Probably because it goes through functions like the + function and the - function, so the argument &T can be treated as T.
  • You can also lend editing rights.
    • Interesting.
    • While lending, the original value cannot be edited.
      • The idea is to have only one entity with editing rights.
    • When the entity that was lent is dropped, the editing rights are returned.
    • When getting/setting the original value through the entity that was lent, you use *.
  • Rules:
    • In Rust, you can have either one mutable reference or multiple immutable references, but not both at the same time.

    • References must not outlive the owner.