Rust, Software Development

Rust Ownership is Easy! Don’t Panic!

The Ownership concept in Rust is easy to grasp! Wait until you get to Rust lifetimes! When we talk about ownership in Rust, we generally mean – a variable owns a value. Seemingly nothing special, right? But the unique part about this concept is that Rust only allows one owner for a value at a time in your application codes. As we assign this value, we move the value, changing the owner.

So, how does Rust enforce this one-value-one-owner? Nope, not at runtime. Rust enforces ownership via the Rust compiler. The compiler does the checks to ensure a value has only one owner, and codes do not refer to the previous owners (if any).

Rust Ownership Rules

Now, we know that the Rust compiler enforces this one-value-one-owner. But that is not the whole story. These are the ownership rules that we programmers must bear in mind.

  1. Each value in Rust has an owner, which is usually a variable.
  2. There is only one owner of the value at a time.
  3. When the variable (owner) goes out of scope, the value goes away and is no longer available (or accessible) unless the value changes owner beforehand.

How are you holding up to this point? No sweat, right? Okay, let’s summarize.

Rust ownership is about one-value-one-owner at a time! Furthermore, it has three rules for enforcement that we must bear in mind. Finally, the compiler generally enforces these rules.

Rust References

References are generally variables. They refer to values! The post What Are References In Rust And How To Use Them? will give you more insight into Rust, references, and ownership. Read on.

Learn Ownership by doing

It isn’t easy to retain something we learned when we don’t use it! Learn ownership by doing – declare and use variables in Rust.

Rust Ownership – Move a Value,  Change The Owner

By default, when we move a value between variables, we move the value between different owners. Copying a value and assigning it to another variable does not change the original data owner. In this case, we are creating a new value with its sole owner. Here is an example of “moving a value” on the post – Things You Need To Know About Strings When Learning Rust.

Still confused?

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like