Sign in

Ownership, borrowing, and the borrow checker

Suggest an edit

Rust's borrow checker is the part of the language that feels like it's fighting you. It rejects code that looks fine, with errors that mention "lifetimes" and "cannot borrow as mutable more than once" without explaining how to fix it. Underneath, it enforces two rules, and the handful of borrow patterns that trip up almost every new Solana developer each trace back to them.

What the borrow checker is for

Most languages let you do whatever you want with memory and crash at runtime if you make a mistake. C and C++ are notorious for this. Garbage-collected languages like JavaScript and Go hide the problem by making memory management automatic, at the cost of a runtime garbage collector you can't easily reason about.

Rust takes a third approach. It tracks who owns each piece of memory at compile time, enforces a small number of rules about how that memory can be shared, and rejects code at compile time that would have caused a runtime bug in C. There's no garbage collector and no runtime cost. The price is that you have to write code the compiler can prove is safe, which sometimes means restructuring code that would have been fine in another language.

For Solana programs specifically, the borrow checker matters because Anchor handlers receive a Context<T> containing references to a set of accounts. The runtime has loaded those accounts into memory and is letting your code read and write them. Anchor uses Rust's references and lifetimes to model who can touch which account, when, and for how long. Most of the time this is invisible, but occasionally you'll write code the compiler rejects, and you'll need to understand why.

The ownership rule

Every value in Rust has exactly one owner. When the owner goes out of scope, the value is dropped (freed). If you assign one variable to another, ownership moves. The original binding is no longer usable.

rust
let s1 = String::from("hello");
let s2 = s1;             // ownership moves from s1 to s2
// println!("{}", s1);   // compile error: s1 has been moved
println!("{}", s2);      // fine: s2 owns the string now

For primitive types like integers and booleans, this rule is relaxed via the Copy trait. Copying a u64 makes a duplicate, so let a = 5; let b = a; leaves both usable. But for owned types that hold heap data, the move is real, and you can't use the original binding afterward.

In Anchor code, you mostly don't move things around. You operate on accounts via references, which is the next concept.

References: borrowing without taking ownership

Most of the time you don't want to move ownership. You want to look at a value, or modify it, then give it back. Rust calls this borrowing, and uses the & syntax.

rust
let config = &ctx.accounts.config;          // immutable reference
let position = &mut ctx.accounts.position;  // mutable reference

let mint = config.rddk_mint;                // read through immutable ref
position.amount = 42;                       // write through mutable ref

&T is an immutable (shared) reference. You can read but not modify. &mut T is a mutable (exclusive) reference. You can read and modify.

The two rules of references:

  1. You can have any number of immutable references to a value at the same time.
  2. If you have a mutable reference, you can have no other references (mutable or immutable) at the same time.

These rules are what the borrow checker enforces. They prevent data races and aliasing bugs at compile time. They are also the source of nearly every borrow-checker error you'll see.

Rust borrowing rules: many readers, no writer vs one writer, no readersTwo side-by-side panels compare Rust's reference rules with code examples. The left panel shows three shared references (&config) compiling fine, and the right panel shows a mutable reference (&mut config) alongside another reference being rejected with a borrow error. The two reference rules, side by side Many readers, no writer Any number of &T at once. let a = &config; let b = &config; let c = &config; // all three can read // none can write ✓ compiles No two threads can disagree about a read-only value. One writer, no readers If &mut T exists, nothing else. let m = &mut config; let r = &config; // ERROR: can't borrow // while m is alive ✗ rejected The writer would race against any reader.

In Anchor code, you typically write let user_state = &mut ctx.accounts.user_state; when you need to modify a field, and let config = &ctx.accounts.config; when you only need to read. The &mut only satisfies the compiler. For the change to be saved, the field also needs #[account(mut)] in the Accounts struct: without it the handler still compiles and runs, but Anchor does not write the account back, as account constraints shows.

The Solana runtime applies the same idea to accounts. A transaction marks each account as read-only or writable, as the instructions and transactions lesson described. Any number of transactions can read the same account in parallel, and transactions that write to the same account run one after another.

Lifetimes and the 'info you see everywhere

Every reference has a lifetime: the span of time during which the reference is valid. Usually you don't write lifetimes: inside a function body the compiler infers them, and in function signatures a few fixed rules, called lifetime elision, fill them in. Sometimes it needs help, and that's when you see explicit lifetime annotations like 'a or 'info.

In Anchor, the lifetime you'll see in every Accounts struct is 'info:

rust
#[derive(Accounts)]
pub struct Stake<'info> {
    #[account(mut)]
    pub user: Signer<'info>,

    #[account(mut)]
    pub user_state: Account<'info, UserState>,

    pub system_program: Program<'info, System>,
}

The 'info lifetime says: "every reference in this struct lives for the same span of time, namely the duration of the instruction." When Anchor loads accounts from the transaction, it gives them all the same lifetime, and you tag your struct with 'info to say "I'm holding references to those accounts."

You don't invent your own lifetime names in normal Anchor code. You write 'info because that's the convention Anchor established, and the macro layer ties it to the right thing. The lifetime parameter is mostly boilerplate. When you copy an Accounts struct from documentation, the 'info is part of the template.

Two borrow-checker errors you will hit

Here are the patterns that cause borrow-checker errors for most Solana developers in their first week.

1. Two mutable borrows of ctx.accounts

error[E0499]: cannot borrow `*ctx.accounts` as mutable more than once at a time

The pattern that triggers it is a method on the Accounts struct that takes &mut self, called while you still hold a reference to one of the struct's fields. A method is a function declared in an impl block and called with a dot, and its &mut self parameter is a mutable reference to the value it is called on:

rust
impl<'info> Process<'info> {
    fn bump_count(&mut self) {
        self.user_state.count += 1;
    }
}

pub fn process(ctx: Context<Process>) -> Result<()> {
    let position = &mut ctx.accounts.position;
    ctx.accounts.bump_count();  // ERROR
    position.amount = 100;
    Ok(())
}

You took a mutable borrow of ctx.accounts.position, and it is still alive because the last line writes through it. Calling bump_count takes a second mutable borrow, this time of the whole ctx.accounts, because a &mut self method borrows every field of the struct, position included. The compiler looks only at the method's signature, so it does not see that bump_count never touches position.

Mutable borrows of two different fields don't conflict. The compiler tracks each field of ctx.accounts separately, so this version compiles:

rust
pub fn process(ctx: Context<Process>) -> Result<()> {
    let user_state = &mut ctx.accounts.user_state;
    let position = &mut ctx.accounts.position;

    user_state.count += 1;
    position.amount = 100;
    Ok(())
}

To fix the error, don't hold a field reference across the method call. Call the method first, then write to the field:

rust
pub fn process(ctx: Context<Process>) -> Result<()> {
    ctx.accounts.bump_count();
    ctx.accounts.position.amount = 100;
    Ok(())
}

Binding let position = &mut ctx.accounts.position; after the call works too. What matters is that no field reference is still in use while the method runs.

2. Borrowing while iterating

error[E0502]: cannot borrow `ctx.accounts.poll` as mutable because it is also borrowed as immutable

The pattern that triggers it:

rust
let votes = &ctx.accounts.poll.votes;
for vote in votes {
    if vote.invalid {
        ctx.accounts.poll.votes.remove(some_index);  // ERROR
    }
}

You're iterating over votes, which holds an immutable borrow of ctx.accounts.poll.votes, while also trying to take a mutable borrow of the same vector to remove from it. The message names ctx.accounts.poll, the account that holds the vector, because the mutable borrow goes through it. The compiler refuses because modifying the vector during iteration would invalidate the iterator.

To fix it, collect the indices to remove first, then remove them after the loop ends.

rust
let mut to_remove = Vec::new();
for (i, vote) in ctx.accounts.poll.votes.iter().enumerate() {
    if vote.invalid {
        to_remove.push(i);
    }
}
// Iteration is done, the immutable borrow is released.
for i in to_remove.iter().rev() {
    ctx.accounts.poll.votes.remove(*i);
}

The .rev() matters because removing from a Vec shifts later indices down. Removing from the end first keeps the earlier indices valid.

For this case Vec has a method that does both steps. retain keeps the elements for which the closure, the inline function |vote| !vote.invalid, returns true and removes the rest, with no index list:

rust
ctx.accounts.poll.votes.retain(|vote| !vote.invalid);

When the compiler rejects a borrow, look for overlapping references

You don't need to track lifetimes by hand, the compiler does that. If the compiler complains about a borrow, the first question to ask is: how long am I holding each reference, and do any of them overlap with another reference to the same data? Almost every borrow error reduces to a mutable reference that is alive at the same time as another reference to the same data.