Bindings in Rust: Much More Than Just Variables

References, borrowing, and lifetimes

The French version of this page is available here

This post is the fourth and last episode of a series of 4. If needed, start with episode 1. The list of episodes is at the end of the page.

TL;DR

  • To lend a binding without giving away its ownership, we pass a reference: &vec0 to read, &mut vec0 to modify.
  • Reference rule : At any given time you can have either one mutable reference (writer) or multiple immutable references (readers).
  • After the call, vec0 is usable again: this is the implicit reborrow.
  • The binding and the reference each have their own mutability: mut s: &str has nothing to do with s: &mut String.
  • When a function returns a reference, we sometimes need to annotate lifetimes so that the compiler can prove the reference will remain valid.

Table of Contents

Where Are We?

In the previous episodes we saw that a binding links a name to the state of a concrete instance and that it carries properties of mutability (episodes 1 and 2) and of ownership (episode 3). To modify a vector, the function fill_vec() of the Rustlings exercise became its owner (move) and then gave it back. In this episode we switch to another example to see how to lend a binding rather than give it away.

Mutability of references

If you haven’t already, I highly recommend reading this book.

Coding Interview Patterns

I’ll spare you the details, but in one of the bonus features in Chapter 1, which deals with “Two Pointers,” there’s an exercise where we’re asked to group all the zeros we could find at the end of a vector. You can take a look at this puzzle here in Rust or here in Python.

Below is a solution in Rust

  • In the function main() we create a binding vec0 that binds the name vec0 to the state of a concrete instance of type Vec<i32>.
  • You notice that when it is created, we give the binding ( let mut vec0) the property mut. We can therefore modify the state of the vector.
  • In a very original way, there is then a function named shift_zeros_to_the_end() to which we pass as an argument something based on vec0 (we will come back to this in 2 minutes)
  • Unlike fill_vec(), the function does not return anything.
  • On the other hand, “Abracadabra!”, on the last line assert allows us to check that the 0s have been pushed to the bottom of the binding vec0
fn main(){
    let mut vec0 = vec![1, 0, 5, 0, 3, 12];
    shift_zeros_to_the_end(&mut vec0);
    assert_eq!(vec0, [1, 5, 3, 12, 0, 0]);
}

fn shift_zeros_to_the_end(nums_in: &mut Vec<i32>){
    let mut left = 0;
    for right in 0..nums_in.len(){
        if nums_in[right] != 0 {
            nums_in.swap(left, right);
            left += 1;
        }
    }
}
  • The function signature shift_zeros_to_the_end() indicates that it expects as a parameter a named binding nums_in which is linked to, I don’t really know what, based on Vec<i32>
  • The code has no importance here
  • Just note that once in the body of the function, we use it nums_in as a mutable vector (we can exchange the contents of 2 cells for example)
  • In the end, everything happens as if the function returned nothing

Given everything we have already explained, we will allow ourselves to speed up a little and focus our attention on just two lines.

  • shift_zeros_to_the_end(&mut vec0);
  • fn shift_zeros_to_the_end(nums_in: &mut Vec<i32>)

About shift_zeros_to_the_end(&mut vec0);

As a reminder, in the first code, main() we had a line like

    let vec1 = fill_vec(vec0);

Here we have a line like this

    shift_zeros_to_the_end(&mut vec0);

It’s not better or worse. The thing is, when the function returns, we don’t have a new binding. We continue to use the original binding ( vec0). However, we must give the function shift_zeros_to_the_end() the means to be able to modify the state of the concrete instance of the type. In other words, I lent you my Ferrari and I give you permission to clean it.

The idea is that this way of expressing things may well reflect our intention (“Here are the keys. Don’t forget to vacuum the Ferrari before you give it back.”) but hey, it’s a bit difficult in terms of writing (there’s even a little Klingon side to it…).

Klingon

In fact, here, we don’t want to give up ownership of the binding, we just want to lend it temporarily (while the function shift_zeros_to_the_end() modifies the state of the concrete instance). In Rust, this is done by passing as an argument, not the binding (if we pass it, it is moved and we lose it) but a reference to the binding.

If I take the ALU (arithmetic logic unit) from the Three-Body Problem in episode 2, I use a single sheet in the workbook where I write an integer (the coordinates) that will allow the recipient to find my binding in the field. By doing this, he knows where to find it and he can work on it. When he has finished, the rider returns to empty (no value returned). This is the signal for me that I can continue my work but using the modified version of my original binding. Everything therefore goes well as if I had lent the binding.

From a syntax point of view, to pass a reference to a binding rather than a binding itself, we use the notation &my_binding.

Well then why do I see it written in the code &mut vec0? You’re a big boy… I’ll let you think about it… Done? No? Still not? Okay, what happens if in the function main() we write a line like:

    shift_zeros_to_the_end(&vec0);

What is the philosophy, the mindset of Rust (compared to C++ for example)? A bit like what we do… We talked about it in episode 1. Yes, very well…

By default, everything is immutable. And so if we write the previous line of code, we tell the compiler that we want to lend the Ferrari but we prohibit any modification. And of course, it will not pass the compilation because the compiler will detect that the signature of the function shift_zeros_to_the_end(nums_in: &mut Vec<i32>) is not respected (there is one &mut that hangs around).

Furthermore, even without the recipient’s signature, Rust requires that I explicitly express the modification permissions I am giving. Since I want to lend the binding vec0 I will pass a reference and since I want to allow modification of what it refers to I must write shift_zeros_to_the_end(&mut vec0).

Isn’t that a bit dangerous?…What happens if we give multiple references that could modify the same binding… Well done, I’m proud of you. You’re starting to think like Rust’s borrow checker. I even think you can answer your question. What would be acceptable from your point of view? Yes, well done again, there’s a rule that says:

Reference Rule

At any given time you can have either one mutable reference (writer) or multiple immutable references (readers).

In plain English, this means that during the static analysis of code, we will follow the loans and that during the execution of the program, we will only be allowed to have a single reference capable of modifying the concrete instance to which it points, or else, to have several references capable of reading the content of the same concrete instance. Between practice, this means that we cannot have a writer and 2 readers. It is either a writer or 2 readers (cheese or dessert but not both).

Um… If I lend a &mut, why can I still use it vec0 afterward? It should have been “consumed” and no longer be available. Right? Well then… You’ll be able to show off at the next family meal… In fact, when you lend a binding vec0 as a &mut vec0, Rust performs what’s called an implicit reborrow :

  • during the call to shift_zeros_to_the_end(&mut vec0), exclusive access to the content is temporarily transferred to the function
  • when the function exits, the reborrow ends, and the binding vec0 becomes accessible and usable normally again in main()
  • Unlike a move, vec0 it is not lost after the call. It simply regains its initial usage rights.

Notes: I confirm to you

  • it is &mut and not mut&
  • for a mutable reference you will see my_function(&mut bob) with a space
    • &mut is a compound operator in Rust
    • &mut is a single “logical keyword”, which reads “mutable reference to”
  • for an immutable reference you will see especially my_function(&bob) without a space whereas shift_zeros_to_the_end(& vec0) is just as legal but not or very little used (I don’t know why, it must be historical)

About fn shift_zeros_to_the_end(nums_in: &mut Vec<i32>)

It’s going to be fast. Very fast. Because from now on, we are strong, very strong…

The function has a single parameter which is an immutable binding that binds the name nums_in to the state of a concrete instance of type &mut Vec<i32>. It is very important to see here that the binding is immutable but that the concrete instance to which the name num_in is bound is, itself, mutable.

What, what, what… I didn’t understand anything. In episode 3 we had

fn fill_vec(mut vec_in: Vec<i32>) -> Vec<i32>{...}

And we said in the comments: vec0 is a mutable binding that links the name vec0 to the complete state of a concrete instance of type Vec<i32>.

Here, there is no mut in front of nums_in so nums_in it is an immutable binding. Then the binding associates the name nums_in with what? To the state of a concrete instance of the type &mut Vec<i32>. In the case of a reference type (mutable or not) on a thing, a concrete instance is the reference itself. So, I repeat: nums_in is an immutable binding that connects the name nums_in to a concrete instance of type &mut Vec<i32>.

The binding is not mutable but the state of Vec<i32> is mutable through the reference.

The solution with associated comments


// the function use an immutable binding that links the name nums_in to the state of an instance of type ``&mut Vect<i32>``
// The binding nums_in is immutable, but it holds a mutable reference
// This means we can mutate the Vec it points to, but we cannot reassign nums_in itself
// nums_in cannot be reassigned to point to another Vec
// but the Vec it refers to can be mutated (e.g. via push, swap, etc.)
fn shift_zeros_to_the_end(nums_in: &mut Vec<i32>){
    let mut left = 0;
    for right in 0..nums_in.len(){
        if nums_in[right] != 0 {
            nums_in.swap(left, right);
            left += 1;
        }
    }
}

fn main(){
    let mut vec0 = vec![1, 0, 5, 0, 3, 12]; // vec0 is a mutable binding so it can be passed as &mut
    shift_zeros_to_the_end(&mut vec0);      // we pass a mutable reference to allow the function to mutate the Vec
    assert_eq!(vec0, [1, 5, 3, 12, 0, 0]);  // values have been rearranged in-place
}

Little million dollar question…

qui veut gagner des millions

What if the function main() looks like this:

fn main(){
    let vec0 = vec![1, 0, 5, 0, 3, 12];
    shift_zeros_to_the_end(&mut vec0);
    assert_eq!(vec0, [1, 5, 3, 12, 0, 0]);
}

Yes, well done… It doesn’t compile…

Yes, but why? Yes, well done again! We create an immutable binding vec0 that we then pass as a mutable reference to the function shift_zeros_to_the_end(). The compiler rightly points out to us that we shouldn’t take it for an fool, that it has seen our shenanigans and that consequently it stops the compilation. Not one to hold a grudge, it indicates a solution which consists of adding a mut in front of vec0.

At this point, regarding the binding, you must keep in mind

  1. It associates a name with the state of an instance of a type
  2. It adds properties
    • of mutability
    • of ownership
    • of borrowing
    • …
  3. Static code analysis ensures that the properties of the bindings are respected.

For the fun…

The code below shows 2 possible implementations.

Either you pass the binding by reference or you move it. They both do the job.

However, we can notice that in the version _byref we only push a pointer to the binding onto the stack (8 bytes on a 64-bit OS).

In the _bymove stack, the control structure, which includes a pointer, a length, and a capacity, is pushed onto the stack. All three are encoded with 8 bytes on a 64-bit OS. In the end, 24 bytes are pushed onto the stack.

If the function needs to be called many times per second, it is probably better to use the version _byref. But before going any further, you need to measure (do a bench).

Otherwise, personally I prefer the version _byref because I find that it is the one that best expresses my intention.

fn shift_zeros_to_the_end_byref(nums_in: &mut Vec<i32>){
    let mut left = 0;
    for right in 0..nums_in.len(){
        if nums_in[right] != 0 {
            nums_in.swap(left, right);
            left += 1;
        }
    }
}

fn shift_zeros_to_the_end_bymove(mut nums_in: Vec<i32>) -> Vec<i32>{
    let mut left = 0;
    for right in 0..nums_in.len(){
        if nums_in[right] != 0 {
            nums_in.swap(left, right);
            left += 1;
        }
    }
    nums_in
}

fn main(){
    let mut vec0 = vec![1, 0, 5, 0, 3, 12];
    shift_zeros_to_the_end_byref(&mut vec0);
    assert_eq!(vec0, [1, 5, 3, 12, 0, 0]);

    let vec1 = vec![1, 0, 5, 0, 3, 12];
    let vec2 = shift_zeros_to_the_end_bymove(vec1);
    assert_eq!(vec2, [1, 5, 3, 12, 0, 0]);
}

The lifetime property of bindings

We’ll start with a simple problem of comparing the length of strings. Below is an example of code that works.

fn longest(s1: String, s2: String) -> String {
    if s1.len() > s2.len() { s1 } else { s2 }
}

fn main() {
    let s1 = String::from("to infinity");
    let result;

    {
        let s2 = String::from(", and beyond!");
        result = longest(s1, s2);
        println!("Longest: {}", result);
    }
    println!("Longest: {}", result);
}

There are no traps or complicated things that we haven’t seen.

  • s1 is an immutable binding that binds the name s1 to the state of a concrete instance of type String.
  • We start by creating an immutable binding that links the name result to the state of a concrete instance of the type “I don’t know yet, we’ll see later”
  • We create an artificial scope with two curly braces. This will be especially useful in the last example. Here, it’s just so the codes in the examples are very similar.
  • s2 is an immutable binding that binds the name s2 to the state of a concrete instance of type String.
  • We call a function longest to which we pass the 2 bindings
  • The return binding of the function longest is moved in result (this is when the compiler deduces that result will be a binding to the state of an instance of a String type)
  • We display
  • We get out the artificial scope
  • We display

Concerning the function, longest it receives 2 immutable bindings on String types (well, I’ll keep it short, you get the idea) and it returns a binding of type String.

  • The thing to note is that in Rust the if are expressions, not statements.
  • In other words, one if returns a value and that is precisely what is done in the single line of code
  • Also note that there is no ; at the end of the line because the value of the if expression is the returned binding

Everything is fine and we can read:

Longest: , and beyond!
Longest: , and beyond!

Now, imagine that for some reason we are asked to rewrite the function longest() so that it takes as parameters bindings whose end of the link is a string slice ( &str for those in the know)

Here is an example of code that doesn’t seem too bad…I won’t comment, it’s almost a copy and paste of the previous code.

fn longest(s1: &str, s2: &str) -> &str {
    if s1.len() > s2.len() { s1 } else { s2 }
}

fn main() {
    let s1 = String::from("to infinity");
    let result;

    {
        let s2 = String::from(", and beyond!");
        result = longest(&s1, &s2);
        println!("Longest: {}", result);
    }
    println!("Longest: {}", result);
}

There’s just one small detail, nothing at all… It doesn’t compile and this is the message displayed:

Compiling playground v0.0.1 (/playground)
error[E0106]: missing lifetime specifier
 --> src/main.rs:1:35
  |
1 | fn longest(s1: &str, s2: &str) -> &str {
  |                ----      ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `s1` or `s2`
help: consider introducing a named lifetime parameter
  |
1 | fn longest<'a>(s1: &'a str, s2: &'a str) -> &'a str {
  |           ++++      ++           ++          ++

For more information about this error, try `rustc --explain E0106`.
error: could not compile `playground` (bin "playground") due to 1 previous error

I’ll let you read… Done?

The compiler tells us that the function returns a reference, which is all very well, but hey, he’d like to be 100% sure that the reference that will be returned will be a reference to data that, at the time of return, will still be valid data. Since he can’t figure it out on his own, he asks us to annotate the function signature with the lifetimes of the bindings concerned.

He even gives us an example that is correct. In fact, the function returns either or depending on the case s1 or s2. So the returned binding and the parameters must have the same lifetimes.

Trust in me, just in me…🎹 Copy and paste the code below. It should work.

fn longest<'t>(s1: &'t str, s2: &'t str) -> &'t str {
    if s1.len() > s2.len() { s1 } else { s2 }
}

fn main() {
    let s1 = String::from("to infinity");
    let result;

    {
        let s2 = String::from(", and beyond!");
        result = longest(&s1, &s2);  // OK s1 and s2 are still living
        println!("Longest: {}", result);
    }                               // <- s2 goes out of scope

    // println!("Longest: {}", result);       // NOK result is s2 dependant
}

Here’s what happens in the signature:

  • <'t> : this introduces a lifetime parameter t that will be used to link the lifetimes of parameters and return values ​​together
  • s1 : &'t str : The first parameter s1 is a string slice that must live at least as long as t
  • s2 : &'t str : The second parameter s2 is a string slice that must live at least as long as t
  • -> &'t str : The function returns a string slice that must live at least as long as t

At runtime, in the console, we see Longest: , and beyond!

Now to really understand this story about binding lifetimes, delete the comment on the last line. This stops compiling and we get the following message:

Compiling playground v0.0.1 (/playground)
error[E0597]: `s2` does not live long enough
  --> src/main.rs:11:31
   |
10 |         let s2 = String::from(", and beyond!");
   |             -- binding `s2` declared here
11 |         result = longest(&s1, &s2);  // OK s1 and s2 are still living
   |                               ^^^ borrowed value does not live long enough
12 |         println!("Longest: {}", result);
13 |     }                               // <- s2 goes out of scope
   |     - `s2` dropped here while still borrowed
14 |
15 |     println!("Longest: {}", result);       // NOK result is s2 dependant
   |                             ------ borrow later used here

For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` (bin "playground") due to 1 previous error

You’re starting to get used to it now. I’ll let you read…

The compiler is really smart (personally I am amazed).

  • On line 10 it points to the declaration of s2 (checks but line 10 is in the artificial scope which starts at line 9 and stops at line 13)
  • It clearly notices that on line 11 we use the binding s2
  • Finally, it indicates just below the second brace of the artificial scope that it s2 no longer exists
  • So he points to line 15, takes out the aluminum ruler and slaps us on the wrist because he is now able to prove to us that we are not respecting the contract we signed with him.
    • We had annotated the function signature with the lifetimes
    • We promised, swore, spat that s1, s2and result had the same lifetime t
    • And yet… And yet in the code, the compiler is able to prove that the binding s2 does not have the same lifetime as the binding result

At this point, regarding the binding, you must keep in mind

  1. It associates a name with the state of an instance of a type
  2. It adds properties
    • of mutability
    • of ownership
    • of borrowing
    • of lifetime
  3. Static code analysis ensures that the properties of the bindings are respected.

Variations on mutability

We’ve seen signatures like (mut nums_in: Vec<i32>) -> Vec<i32> and (nums_in: &mut Vec<i32>). Would it make sense to write something like (mut nums_in: &Vec<i32>) or (mut str_in: &mut Vec<i32>), and what could that be used for?

Here, treat yourself. You have all the elements you need to analyze the situation. Always make sure to distinguish between the mutability of the binding and the mutability of the reference. Take your time; we’re in no rush.


// The binding str_in associates the name str_in with the state of a concrete instance of type reference to a String.
// str_in is a not mutable binding; it cannot be reassigned to an other &String.
// The reference to the String is also not mutable; the content of the String cannot be modified through this reference.
fn dont_change(str_in: &String){
    println!("{}", str_in); // Reads and prints the string. Cannot modify
}

// The binding str_in associates the name str_in with the state of a concrete instance of type mutable reference to a String.
// str_in is a not table binding; it cannot be reassigned to another &mut String.
// The reference to the String is mutable. The content of the string can be modified using this reference
fn change(str_in: &mut String){
    str_in.push_str(" power!"); // Appends text to the original String
}

// The binding str_in associates the name str_in with the state of a concrete instance of type reference to a string slice (&str)
// str_in is a mutable binding; it can be reassigned to another string slice (&str)
// we cannot modify the data pointed to by the slice
fn change_view(mut str_in: &str) {
    str_in = &str_in[1..3];   // Rebinds str_in to a substring of the original
                              // This is NOT a let. This is an reassignment
    println!("{:?}", str_in); // Prints the new slice
}



// The binding str_in associates the name str_in with the state of a concrete instance of type &mut String.
// str_in is a mutable binding; it can be reassigned to another mutable reference to a String.
// The reference itself is mutable: the content of the String can be modified through this reference.

// The binding other associates the name other with the state of a concrete instance of type &mut String.
// other is a not mutable binding; it cannot be reassigned to an other mutable reference to a String.
// The reference itself is mutable: the content of the String can be modified through this reference.

// We need to annotate the lifetime because we manipulate two mutable references.
fn change_and_reassign<'a>(mut str_in: &'a mut String, other: &'a mut String) {
    // Modify the original String
    str_in.push_str(" modified");
    println!("After modification                         : {}", str_in);

    // Reassign str_in to point to another mutable String
    str_in = other;
    str_in.push_str(" changed");
    println!("After reassignment and second modification : {}", str_in);
}


fn main() {
    // Create a mutable String binding
    let mut my_str = String::from("Banana");

    // Pass an immutable reference to a function that reads the string
    dont_change(&my_str);

    // Pass a mutable reference to allow the function to modify the String
    change(&mut my_str);
    println!("{}", my_str); // Print my_str once modified String

    // Pass an immutable reference (as a slice) to a function that creates a view into the string
    change_view(&my_str);



    let mut my_str = String::from("hello");
    let mut another_str = String::from("world");

    // Pass two mutable references
    change_and_reassign(&mut my_str, &mut another_str);

    // After the function, let's print the original variables
    println!("my_str      : {}", my_str);
    println!("another_str : {}", another_str);

}

I’ll let you read the comments for the first 3 functions. Normally, there shouldn’t be any problems.

However, in order to be exhaustive, I absolutely wanted to have an example with 2 mut in the function signature. One for the mutability of the binding and another for the mutability of the reference. It took a lot of fighting with the compiler and I had no other choice but to specify the lifetimes of the references.

Good news, you’ve just seen the “lifetime” property of bindings. So you have everything you need to get your teeth into the function change_and_reassign().

Conclusion

That’s it, we’ve reached the end of the series. Well done for hanging in there.

For the rest, concerning the binding I hope to have convinced you that:

  1. It associates a name with the state of an instance of a type <T>
    • I say state rather than value because it works better with Vec<T>, String…
    • Think about the hash code if necessary
  2. It adds properties
    • of mutability
    • of ownership
    • of borrowing
    • of lifetime
  3. During static analysis, different tools (lifetime checker, borrow checker, etc.) ensure that the properties of the bindings are respected.

I propose that from now on, in the context of Rust, I no longer speak of variables but only of bindings.

Indeed, from my point of view the word “variable” is inherited and more appropriate for classic imperative languages ​​(C, C++, Python…), where a variable is:

  • a name
  • which references a memory cell
  • in which the value can change

If we talk about binding (and we constantly keep in mind binding = name + value + ownership + mutability + borrowing + lifetime) we are better able to ask the right questions or reason about a compiler message. A binding in Rust is a contract of possession and use.

The Posts Of The Series

  • Episode 1: bindings rather than variables, binding mutability
  • Episode 2: parameter passing, stack, heap, and the state of an instance
  • Episode 3: ownership, move, and copy
  • Episode 4: references, borrowing, and lifetimes

Back to top

Published on: Dec 2 2026 at 11:00 AM | Last updated: Dec 2 2026 at 05:26 PM

Copyright © 1964-2026 - 40tude