Understanding Rust: ownership, borrowing, lifetimes

  • They make you think in the right way. After some Rust experience, you will often find yourself trying to apply the same concepts when developing in other languages, even if they are not built right into the syntax.
  • They make your code safe. Except for several pretty rare corner cases all of your “safe” Rust code is guaranteed to be free of the bugs we’re talking about.
  • Rust feels as pleasurable as high-level languages with garbage collection (who am I kidding by saying JavaScript is pleasurable?), yet being as fast and as native as other low-level compiled languages.

Ownership

Borrowing

  • It allows us to have multiple references to a resource while still adhering to the “single owner, single place of responsibility” concept.
  • References are similar to pointers in C.
  • A reference is an object too. Mutable references are moved, immutable ones are copied. When a reference is dropped, the borrow ends (subject to the lifetime rules, see the next section).
  • In the simplest case references behave “just like” moving ownership back and forth without doing it explicitly.

Lifetimes

Random additional notes

  • You can’t move out of a borrowed value, because after the borrow ends the value must stay valid. You can’t move out of it even if you move something back in the very next line. But there is mem::replace that lets you do both at the same time.
  • If you want an owning pointer — something like unique_ptr in C++, there is the Box type.
  • If you want some basic reference counting — like shared_ptr and weak_ptr in C++, there is this standard module.
  • If you really really need to get around the restrictions Rust puts on you, you can always resort to unsafe code.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sergey Bugaev

Sergey Bugaev

More from Medium

Exchange messages with IBM MQ using Rust

Error handling in Solidity is very useful

Solidity – Pure and View Modifiers – Blog | Avantrio

rp-cli: Rust Playground CLI

A Beginner’s Guide to Setting up Rust on Windows.