Tech News
← Back to articles

The Algebra of Loans in Rust

read original related products more articles

The heart of Rust borrow-checking is this: when a borrow is taken, and until it expires, access to the borrowed place is restricted. For example you may not read from a place while it is mutably borrowed.

Over the recent months, lively discussions have been happening around teaching the borrow-checker to understand more things than just “shared borrow”/”mutable borrow”. We’re starting to have a few ideas floating around, so I thought I put them all down in a table so we can see how they interact. I’ll start with the tables and explain the new reference types after.

To clarify the vocabulary I’ll be using:

A “place” is a memory location, represented by an expression like x , *x , x.field etc ;

, , etc ; “Taking a borrow” is the action of evaluating &place , &mut place , &own place etc to a value;

, , etc to a value; A “loan” happens when we take a borrow of a place. The loan remembers the place that was borrowed and the kind of reference used to borrow it. When we take that borrow, the resulting reference type gets a fresh lifetime; as long as that lifetime is present in the type of a value somewhere, the loan is considered “live”;

While a loan is live, further operations on the borrowed place are restricted;

After the loan expires, operations on the borrowed place may be restricted too.

Note: These tables are not enough to understand everything about these new references. E.g. after you write to a &uninit you can reborrow it as &own , and vice-versa; this is not reflected in the tables. Another example: dropping the contents of a place removes any pinning restriction placed on it.

Table 1: Given a reference, what actions are possible with it

... continue reading