Back to Home

Graphical description of ownership and borrowing in Rust

rust · borrowing · ownership

Graphical description of ownership and borrowing in Rust

Original author: Phil Rufflewind
  • Transfer

The following is a graphical description of moving, copying, and borrowing in the Rust programming language . Basically, these concepts are specific only to Rust, being a common stumbling block for many beginners.



To avoid confusion, I tried to keep the text to a minimum. This note is not a substitute for various training manuals, and is only made for those who believe that visually information is perceived more easily. If you just started to study Rust and find these graphs useful, then I would recommend you mark your code with similar schemes for better consolidation of concepts.



Scheme


The picture is clickable, you can enlarge it. You can also get schemes without translation in the form of PNG , SVG or PDF .


The upper two schemes depict two main types of data semantics that are available to us: either moving or copying.


  • The semantics of the displacement semantics (⤳) look very simple. There is no deception here: the semantics of movement seem strange only because most languages ​​allow variables to be used as many times as the programmer wishes. In the real world, this is usually not the case: I can’t just give someone my pen and still use it for recording! In Rust, any variable whose type does not implement a type Copyhas semantics of movement, the behavior of which is shown in the figure.
  • Copy semantics (⎘) are reserved for types that implement traits Copy. In this case, each use of the object will lead to copying, as shown in the diagram - a split.

The two central schemes describe two methods of borrowing an object that you own, and what each of these methods offers.


  • For variable borrowing, I used the lock symbol in order to show that the original object is locked for the entire time of borrowing, which makes it impossible to use it.
  • For the opposite, immutable borrowing , I used the snowflake symbol to show that the original object is just frozen : you can still take immutable links, but you can't move or take mutable references to it.

In both schemes, this is the name that I chose to designate the link lifetime . I specifically used the Greek letter, since, at the moment, there is no syntax to describe specific lifetimes in Rust.


The last two schemes summarize, showing the main differences and common features between the two types of links, both in the form of images and in the form of text. The specifier is “outwardly” important, as you may have internal mutability through things like Cell.


Translator's Note


I would like to express special thanks to Andrei Lesnikov ( @ozkiff ), Serhii Plyhun ( @ snuk182 ) and Sergey Veselkov ( @vessd ) for their help in the translation and subsequent review.

Read Next