Ownership principles

So basically, in this post I will summarize what I have understood, so far, from the reference and docs.

The solely purpose is to reflect on what I have learnt, and receive a feedback/review.

Ownership

  • Every object in Rust has it's owner, that is the owner of a value.
  • There cannot be multiple owners at a time
  • Mutable objects cannot have multiple borrows/references simultaneously
  • There can be multiple immutable borrows/references simultaneously
  • Pointing to a value that is owned by someone else, will move it's ownership to the newly created one and drop/free the previous owner
  • Shared references are not allowed to alter where they point to

That's just a reference and doesn't move anything. You need to pass-by-value to move.

That needs to be Shared references are not allowed to alter where what they point to. Like the difference between const * and * const in C.

I feel summarizing Rust's ownership model can have a lot of nuance if you want it to and depending on how you define things. Personally I dislike being given wrong or incomplete information without at least a heads-up.

With that in mind, I'd adjust your bullet points like so.

  • Every value in Rust has an owner
    • Except arguably static and leaked values, depending on your definition of "owner"/"owned"
  • Typically there is one owner
  • &mut T are exclusive references; it is UB to have anything aliasing an active &mut
    • Reborrows don't result in active aliasing (the reborrowed place is inactive for awhile)
    • Values aren't intrinsically mutable or immutable
      • Bindings like let mut foo kinda-sorta are, but it's more like a lint than anything
  • &T are shared references; they can be aliased
    • Most types are immutable when behind a shared reference
    • However some types feature shared mutability allowing mutation behind a shared reference
      • This ability is used in the synchronization and shared ownership types in particular
  • Values can have move semantics or copy semantics depending on the Copy trait
    • If moved, the original place becomes uninitialized
      • The destructor of the original place is not called
    • If a value is being overwritten, and has a desctrutor, the overwritten value is destructed
4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.