Zeeshan Adil
Book a call
← Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes

Chapter 4 of 16 · Part I, Foundations

Ownership, and the rule that replaced the collector

by Zeeshan AdilUpdated 31 min read
Listen to this articleRust Ownership and Move Semantics for C# Engineers 34 min · read by an AI voice
0:00 / 33:42

The three ownership rules, what a move compiles to, Copy against Clone, and how Drop replaces using, for engineers used to the .NET garbage collector.

The question to keep beside each example is: who owns the value after this line? Start with moves, Copy, and clone, then follow cleanup through Drop. You can skip the compiler internals on your first pass and still understand the ownership rule.

The whole model is three rules. The Rust Book states them as:

  1. Each value in Rust has an owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped.

These rules are the starting point. Borrowing adds constraints on how values can be accessed while references exist, and the compiler checks those constraints too. We'll build up to that in the next chapter.

Code
fn main() {
    let config = String::from("retries=3");   // config owns the buffer
    println!("{}", config);
}                                             // scope ends, buffer freed here

No tracing collector ran. In this straight-line example, config is still initialized at the end of the scope, so Rust drops the String and releases its buffer there. The cleanup is predictable, but releasing an allocation still takes runtime work.

Write the same thing in C#, with a string built at run time rather than an interned literal, and the reference goes out of scope at the closing brace. Nothing is freed at that point. The object becomes eligible for collection, and it will be reclaimed at some later moment chosen by the runtime based on allocation pressure, generation budgets and which latency mode the process is in. The word "eligible" is doing all the work in that sentence. Rust replaced eligible with freed.

Now the part that generates the error message from the first paragraph of this guide:

Code
fn main() {
    let s1 = String::from("hello");
    let s2 = s1;

    println!("{s1}, world!");
}

s2 takes ownership. s1 is dead from that line on, and reading it is the error.

In C# this is fine, because s1 and s2 are two references to one heap object and the collector will deal with it when both are unreachable. In Rust, allowing it would mean two owners, which would mean two deallocations of one buffer. A double free. So the compiler moves ownership and marks s1 as no longer usable.

The diagnostic is worth reading line by line, because rustc puts more into it than you expect and most people skim it.

Code
error[E0382]: borrow of moved value: `s1`
 --> src/main.rs:5:16
  |
2 |     let s1 = String::from("hello");
  |         -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 |     let s2 = s1;
  |              -- value moved here
4 |
5 |     println!("{s1}, world!");
  |                ^^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let s2 = s1.clone();
  |                ++++++++

Three spans and a help line, four separate facts. The first span, on the declaration, tells you the reason: String is not Copy, which is a property of the type, not of this line. The second span tells you where the value left. The third span, the one with the carets, is where you tried to use it, and the verb is precise: borrowed, not used, because println! takes its arguments by reference. The help line offers the escape hatch and is honest about it being a cost rather than a fix.

For this example, the next step depends on your intent:

  • To transfer the string, keep the move and print s2. The result is hello, world!.
  • To let another part of the program read the same string, borrow it instead. The next chapter shows how.
  • To keep two independently owned strings, use s1.clone() and account for the copy.

The common mistake is to apply the compiler's cloning suggestion before deciding which of those three behaviors you want.

Before the move, s1 owns the String. After let s2 = s1, s2 owns it and s1 cannot be used until it is reinitialized. The heap buffer itself does not need to move.
Rust logo © the Rust Foundation, CC BY 4.0; unmodified.

What a move actually compiles to

A move transfers ownership in the language model. For a String, the heap buffer itself does not need to move, but the compiler may copy the value's representation between locations. On common 64-bit targets that representation is currently three words; its exact layout is not a stable promise. The optimizer may remove the copy altogether.

That is the model you should carry, and it is the model the language documentation encourages: the Book says outright that any automatic copying can be assumed to be inexpensive, because Rust never deep-copies for you.

The mechanism underneath is a dataflow analysis on MIR, the compiler's mid-level intermediate representation. rustc tracks moves and initialization as a set of initialized places: assigning to a previously uninitialized local adds it to the set, and moving out of a local removes it. That analysis determines which uses and drops are valid. It does not imply that the generated machine code is always free: a move can copy bytes, and conditional initialization can require drop bookkeeping, as shown below.

The honest version has an asterisk. At the MIR level a move of a non-Copy value is still a copy of its bytes, and LLVM is usually but not always able to delete that copy. Issue 13707, open since 2014, is exactly the request to stop emitting memcpys for moves where the compiler could avoid it. The Copy trait docs say the same thing more gently: both a copy and a move can result in bits being copied in memory, although this is sometimes optimized away.

For a String at 24 bytes, this is noise. For a 4 KB struct moved through five layers of builder methods, it is not, and the fix is the same one you would reach for in C# with a large struct: put it behind an indirection, which in Rust means Box, and move the pointer instead.

Moves in and out of functions

Passing a value to a function moves it, for exactly the same reason assignment does. The parameter is a new binding, and there can only be one owner.

Code
fn consume(s: String) { /* s dropped at the end of this function */ }

fn main() {
    let name = String::from("db-1");
    consume(name);
    println!("{}", name);     // error[E0382]: borrow of moved value: `name`
}

This is where the model first bites. In C#, handing an object to a method copies a reference and settles nothing about who is responsible for it afterwards. In Rust the signature is the contract: s: String takes ownership. The function may drop the value, return it, store it elsewhere, or transfer ownership again.

Returning an owned value transfers it out of the function to the caller. That is how constructors such as String::from work: they build a value and hand ownership to the caller.

If you want to keep something you are passing, there are three options, and choosing between them is most of what writing Rust feels like early on. Borrow it, which is the next chapter and is almost always the answer. Clone it, which allocates a copy and is sometimes exactly right. Or have the function give it back by returning it, which is clumsy and occasionally the clearest thing, particularly for builder chains where fn with_port(mut self, p: u16) -> Self reads better than any alternative.

There is a subtlety here that catches people. Reassigning an initialized variable drops the old value first, immediately, at the point of assignment:

Code
fn main() {
    let mut s = String::from("hello");
    s = String::from("ahoy");    // the "hello" buffer is freed right here
    println!("{s}");
}

The Reference states this as a rule: assignment runs the destructor of its left-hand operand, if it is initialized. In C#, reassigning the variable removes that reference; the old object becomes eligible for collection only when no reachable references remain. Resource cleanup depends on how that type implements disposal and finalization, so explicit disposal is still important. Same line of code, completely different consequence.

Copy, move, clone

Three words that sound like synonyms and are not.

Copy is for types that can be duplicated by copying their bits: integers, floats, bool, char, shared references, and tuples or arrays of those. A copied reference is another reference to the same referent, not an independent copy of the data. They implement the Copy marker trait, and assignment duplicates rather than moves. This is why let x = 5; let y = x; leaves x perfectly usable and you never think about it.

Move is the default for types that are not Copy. Ownership transfers and the moved-from place cannot be used until it is reinitialized. The move may copy the value's own bytes; for an owning pointer it does not deep-copy the allocation it refers to.

Clone is explicit and possibly expensive. a.clone() on a String allocates a new buffer and copies the bytes. Clone::clone may run arbitrary code, and it is deliberately something you have to type.

The rule for whether a type can be Copy is worth internalizing, because the compiler will quote it at you. From the Copy documentation: a type can implement Copy if all of its components implement Copy. The example in those docs is a struct PointList with one field, points: Vec<Point>. Derive Copy on it and you get E0204:

Code
the trait `Copy` cannot be implemented for this type; field `points` does not implement `Copy`

Two consequences fall out of that rule, and both explain things you will hit.

String cannot be Copy because duplicating its bits would duplicate responsibility for one heap buffer, and both copies would try to free it. The same reasoning applies to Vec<T> and Box<T>, and resource-owning types such as File generally cannot be Copy. A plain handle value is not inherently non-Copy; the type's ownership and cleanup rules decide.

Any type implementing Drop cannot be Copy, and the compiler enforces it with E0184. The Drop docs give the reasoning plainly: types that are Copy get implicitly duplicated by the compiler, making it very hard to predict when, and how often, destructors will be executed. A destructor that might run an unknowable number of times has stopped being a destructor.

#[derive(Clone)] generates the obvious thing: an implementation that calls clone on each field. For a generic type it also adds a bound, so #[derive(Clone)] struct Reading<T> { frequency: T } produces an impl that requires T: Clone. That is usually what you want and occasionally not. The Clone docs work through the case where it is wrong: a struct holding a function pointer fn() -> T is cloneable regardless of whether T is, but the derived impl will demand T: Clone anyway. Writing the impl by hand is the fix, and it is three lines.

One more thing about Clone that a C# reader will get wrong on the first read. Clone is not automatically deep. It calls clone on each field, and if a field is an Arc<Mutex<T>>, cloning that field bumps a reference count and gives you a second handle to the same mutable state. The std docs flag this explicitly. So #[derive(Clone)] on a struct full of Arc fields is closer to C#'s MemberwiseClone than to a deep copy, and that is a real source of bugs in shared-state code.

Your C# intuition maps closely if you line them up:

SituationC#Rust
Assign an intcopies the valueCopy, copies the value
Assign a structcopies all fieldsCopy if all fields are, else a move
Assign a class referencecopies the reference, two names for one objectmove, one name for one value
Deep copywrite it yourself, or serialize and deserialize.clone(), if every field clones deeply
Two ownersnormal, the collector sorts it outneeds Rc or Arc. Chapter eleven

That third row is the real change. In C#, var b = a; on a class gives you two names for one object, and that is so normal that you stopped seeing it. Every aliasing bug you have ever debugged, every time a caller mutated a List<T> you thought you owned, lives in that row. Rust's default is the opposite, and the cost is that you have to say what you mean.

Taking a struct apart

Ownership is tracked per field, not only per variable, which is more useful than it sounds and produces error messages nobody expects.

Code
struct Server {
    hostname: String,
    port: u16,
}

fn takes_server(_s: Server) {}

fn main() {
    let server = Server { hostname: String::from("db-1.internal"), port: 5432 };

    let host = server.hostname;
    println!("port is {}", server.port);
    println!("host is {}", host);

    takes_server(server);
}

Line by line: server.hostname moves out, and from that point server is partially moved. Reading server.port still works, because that field was never moved and u16 is Copy anyway. Using server as a whole does not, because there is no longer a whole Server there.

Code
error[E0382]: use of partially moved value: `server`
  --> src/main.rs:15:18
   |
11 |     let host = server.hostname;
   |                --------------- value partially moved here
...
15 |     takes_server(server);
   |                  ^^^^^^ value used here after partial move
   |
   = note: partial move occurs because `server.hostname` has type `String`, which does not implement the `Copy` trait
help: consider cloning the value if the performance cost is acceptable
   |
11 |     let host = server.hostname.clone();
   |                               ++++++++

The word partially in both the header and the label is the compiler telling you it tracked the field, not just the binding. C# has no analogue at all. A field read is a field read, the object stays intact, and if you wanted to null the field out you would have to do it yourself.

If you need the fields separately and no longer need the whole value, you can destructure them at once:

Code
let Server { hostname, port } = server;   // moves both fields, consumes `server`

That form is common enough in real Rust that you should reach for it by reflex.

Now the version that has no easy fix, and teaches the mechanism:

Code
struct Handle(u32);

struct Connection {
    handle: Handle,
    id: u32,
}

impl Drop for Connection {
    fn drop(&mut self) {
        println!("closing connection {}", self.id);
    }
}

fn steal(conn: Connection) -> Handle {
    conn.handle
}
Code
error[E0509]: cannot move out of type `Connection`, which implements the `Drop` trait
  --> src/main.rs:16:5
   |
16 |     conn.handle
   |     ^^^^^^^^^^^
   |     |
   |     cannot move out of here
   |     move occurs because `conn.handle` has type `Handle`, which does not implement the `Copy` trait
   |
help: consider borrowing here
   |
16 |     &conn.handle
   |     +

The reason is worth spelling out because it is the clearest example of the compiler protecting an invariant you wrote yourself. Connection has a destructor. That destructor takes &mut self and will run when the value goes out of scope. If you were allowed to move handle out, drop would later run on a Connection whose handle field is gone, and drop has no way to know. The E0509 documentation states the rule plainly: you have to think of all values whose type implements Drop as single units whose fields cannot be moved.

The safe way out is to make the field optional and take it:

Code
struct Connection {
    handle: Option<Handle>,
    id: u32,
}

fn steal(mut conn: Connection) -> Option<Handle> {
    conn.handle.take()        // leaves None behind, `conn` stays whole
}

Option::take replaces the field with None and hands you the contents, which keeps Connection fully initialized so its destructor stays valid. std::mem::take and std::mem::replace do the same job for non-optional fields. This is the standard shape for any type that owns a resource and has a close or into_inner method, and once you have seen it you will see it everywhere in the standard library.

Drop is using that you cannot forget

The heading is a useful shorthand, with an important exception: Rust normally runs cleanup automatically, but destructors are not guaranteed to run in every situation. In ordinary scope exit, a destructor consists of a call to Drop::drop if the type implements it, followed by automatically generated cleanup for its fields.

Here is a complete program you can paste into a file and run. It exists to show drop order, which is defined precisely and which you will need to reason about the first time two of your values depend on each other.

Code
struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}

struct Pair {
    first: Noisy,
    second: Noisy,
}

impl Drop for Pair {
    fn drop(&mut self) {
        println!("drop Pair");
    }
}

fn consume(n: Noisy) {
    println!("  consume got {}", n.0);
}

fn main() {
    let a = Noisy("a");
    let b = Noisy("b");

    {
        let _inner = Noisy("inner");
        println!("in block");
    }

    println!("value is {}", Noisy("temp").0);

    consume(Noisy("arg"));

    let moved = Noisy("moved");
    consume(moved);

    let _pair = Pair {
        first: Noisy("pair.first"),
        second: Noisy("pair.second"),
    };

    println!("end of main");
}

Output:

Code
in block
drop inner
value is temp
drop temp
  consume got arg
drop arg
  consume got moved
drop moved
end of main
drop Pair
drop pair.first
drop pair.second
drop b
drop a

Five rules are visible in that output, and all five are written down in the Reference rather than being accidents of the current implementation.

The inner block drops _inner at its closing brace, not at the end of main. The temporary Noisy("temp") lives to the end of the statement that created it and no longer. A value moved into consume is dropped by consume, at the end of that function, because parameters live in the scope of the whole function body. The binding moved is not dropped again at the end of main, because the compiler knows it was moved out. And at the end of main, locals drop in reverse declaration order, while the fields of Pair drop in declaration order, after Pair's own drop has run.

Reverse order for locals is not arbitrary. It means a value can safely hold a reference to something declared before it, which is the entire basis of the guard pattern.

Now the same shape in C#, so the comparison is concrete rather than asserted:

Code
sealed class Noisy : IDisposable
{
    private readonly string _name;
    public Noisy(string name) => _name = name;
    public string Name => _name;
    public void Dispose() => Console.WriteLine($"dispose {_name}");
}

sealed class Pair : IDisposable
{
    private readonly Noisy _first = new("pair.first");
    private readonly Noisy _second = new("pair.second");

    public void Dispose()
    {
        Console.WriteLine("dispose Pair");
        _first.Dispose();     // you wrote this line, and the order, by hand
        _second.Dispose();
    }
}

static class Program
{
    static void Consume(Noisy n) => Console.WriteLine($"  consume got {n.Name}");

    static void Main()
    {
        using var a = new Noisy("a");
        using var b = new Noisy("b");

        Consume(new Noisy("arg"));   // never disposed in this example

        using var pair = new Pair();
        Console.WriteLine("end of main");
    }
}

Two differences, in order of how much they cost you.

The Noisy("arg") passed to Consume is never disposed. It becomes garbage, its Dispose never runs, and if it held a socket the socket stays open until the process notices. The C# parameter type alone does not specify who should dispose the object; a configured analyzer such as CA2000 can catch some missed disposal paths. In Rust, fn consume(n: Noisy) transfers ownership to the function, which normally drops the value unless it transfers or deliberately leaks it.

Pair.Dispose is hand-written, and so is the order of its field disposal. Forget a line and you leak a field. Rust's drop machinery normally handles owned fields automatically, though a type's own implementation and leak or termination behavior still matter.

The parts that are the same deserve credit. A local declared with using is disposed at the end of the scope it is declared in, several resources declared in one using statement are disposed in reverse order of declaration, and a return in the middle of a using block still disposes because the compiler rewrites the block into try/finally. If you consistently use using, C# gives you deterministic cleanup too. The difference is the word "if".

The fallback when nobody writes the using is a finalizer, and finalizers are a genuinely worse tool. A class that has one gets an entry in the finalize queue for the collector to process, you get no control over when it runs, and on .NET 5 and later finalizers are not run as part of application termination at all. Which is why the dispose pattern has you call GC.SuppressFinalize(this) the moment you have cleaned up properly: the finalizer is the path you want to avoid taking. Rust has no queue to get onto. The deallocation is a call at a known instruction.

Automatic cleanup makes scoped guards convenient. A MutexGuard, for example, unlocks when it is dropped, so ordinary control-flow exits release it without a separate unlock call. Deliberately forgetting the guard or terminating the process can bypass that cleanup. A transaction handle rolls back on drop unless you called commit, which consumed it. A tracing span closes on drop. A connection checked out of a pool returns itself on drop. Each of those is a type whose only job is to exist for a scope, and each of them is a category of bug that stops being possible.

Panics run drops too. A panic unwinds the stack by default and runs the destructor of every value on the way out, roughly what finally gives you in C# but applied to every value rather than to the blocks you remembered to write. Neither is absolute: an unhandled exception in .NET can tear the process down without running your finally blocks, and Rust has its own escape hatch, a build configured with panic = "abort", which terminates without unwinding and therefore without dropping. That is a deliberate trade for smaller binaries and it is the right choice for some embedded targets, so it is worth knowing which one your profile uses.

The model above was simplified

The claim a few pages back was that the compiler inserts the deallocation at the closing brace. True for the straight-line case, false as soon as control flow gets involved.

Code
fn some_condition() -> bool { true }

fn main() {
    let mut y = Vec::new();
    {
        let x = vec![1, 2, 3];
        if some_condition() {
            y = x;          // x moves into y, sometimes
        }
    }                       // should x be dropped here?
    println!("{y:?}");
}

The compiler cannot answer that at compile time, because the answer depends on a runtime value. What actually happens is a pass called drop elaboration. rustc runs two dataflow analyses, MaybeInitializedPlaces and MaybeUninitializedPlaces, over the MIR. When a place is definitely initialized at a drop point, the drop is emitted unconditionally. When it is definitely uninitialized, the drop is deleted. When the answer is genuinely conditional, the compiler allocates a hidden boolean on the stack, a drop flag, sets and clears it as the value is initialized and moved from, and wraps the drop in a check of that flag.

So there is a run-time cost after all: a boolean on the stack and a branch, in the specific cases where the compiler could not prove the answer. The cost depends on the generated code and workload, so measure it when it matters rather than assuming it is zero. But "zero cost" is not literally true, and it is better to know where the cost lives than to repeat a slogan.

The other simplification was calling the move free. At MIR level it is a byte copy, and the optimizer usually removes it. Usually.

Connections, files, and the resources you must not leak

The place this stops being a language-tour curiosity and starts being an architectural difference is anything that holds a limited, external resource: database connections, file descriptors, sockets, GPU buffers, locks.

In a .NET service, the failure mode is familiar. A SqlConnection is not disposed on some error path. Microsoft's own guidance is blunt about what follows: connections that are not explicitly closed might not be added or returned to the pool. Once the pool is at maximum size with no usable connection available, further requests queue, and if the pooler cannot satisfy one before the connection times out, it throws. Under load that presents as intermittent timeouts on a service that looks healthy, which is what makes it hard to diagnose. .NET has good answers to this. SafeHandle exists so that even a badly written wrapper releases its OS handle when the collector eventually finalizes it, and analyzers flag undisposed locals. They are all mitigations for the fact that Dispose is a method somebody has to call.

In Rust a pooled connection can be a struct whose Drop returns it to the pool. Ordinary early returns, errors propagated with ?, and panics that unwind through the frame run cleanup when they leave the scope. Deliberately leaking the value, aborting, or terminating the process can still skip its destructor, so critical recovery must not depend solely on Drop.

The second-order effect is on API design, and it is bigger than the leak itself. Because you can trust destruction, you can build types whose only purpose is to guarantee a paired operation. Lock acquired and released. Transaction begun and rolled back. Metric timer started and recorded. Buffer checked out and returned. In C# you can write those as IDisposable and they work, right up until a caller in a different team's code forgets the using, at which point the failure is silent and surfaces as a slow leak in production weeks later. The .NET team clearly thinks the guard shape is right. The System.Threading.Lock type added in .NET 9 hands you a disposable scope from EnterScope(), and locking such an object is defined as compiling to exactly using (x.EnterScope()). Same design. One guarantee weaker, because the moment you call EnterScope yourself instead of using the lock statement, writing the using is back to being your job.

The mistakes that come from the C# habit

Cloning to make the error go away. This is the big one, and the compiler even suggests it. A .clone() compiles, the error disappears, and you move on. Grep your own diff for it: a clone() inside a loop, or a cluster of them in one function, usually means you are paying allocations to avoid learning the borrow rules. The fix is usually to change a parameter from String to &str or from Vec<T> to &[T], which is the next chapter. Clone deliberately, when you genuinely need a second independent value, and it is fine.

Expecting assignment to alias. You write let b = a; intending two handles to one thing, then get confused when a is dead. What you wanted was let b = &a; for read-only sharing, or Rc/Arc for genuine shared ownership. The tell is that you are surprised by the error rather than by the design.

Writing C# getters. fn hostname(&self) -> String { self.hostname } is the reflex and it does not compile: E0507, cannot move out of self.hostname which is behind a shared reference. The compiler suggests .clone(). Take the suggestion and you have a getter that allocates on every call. The right signature is fn hostname(&self) -> &str, which is free.

Building an object graph before you have read chapter eleven. Parent pointers, observer lists, a cache whose entries know their owner. All trivial in C#, all a long fight in Rust if you attack them head-on. Recognize it early: if you are hours into lifetime errors on a data structure that is fundamentally a graph, stop and reach for Rc<RefCell<T>>, or for an arena with integer indices, which is what a lot of production Rust does.

Assuming Drop always runs. It does not run on std::process::exit, it does not run under panic = "abort", and it does not run for a leaked value. Do not put anything load-bearing in a destructor that must happen for correctness rather than for tidiness.

Where C# still wins

Three places, and they are not small.

Graphs and shared mutable state. A tracing garbage collector is genuinely better at object graphs with cycles and back-references than ownership is. A doubly linked list, a scene graph with parent pointers, an observer registry, a domain model where entities reference each other freely: in C# these are ordinary code. In Rust they cost you Rc<RefCell<T>>, which moves borrow checking to run time and can panic, or an arena of indices, which trades compiler-checked references for integers the compiler cannot check at all. If your domain is fundamentally a graph, C# is the better tool and saying otherwise is dishonest.

Cleanup that can fail. Drop::drop takes &mut self, returns nothing, and cannot be async. Closing a file can fail, and std::fs::File says outright that errors detected on closing are ignored by its Drop implementation, so you must call sync_all yourself if you care. C#'s Dispose can throw, which is its own problem, but at least the error can reach you.

Async cleanup. This one is a clear win for .NET today. C# has IAsyncDisposable and await using, so a resource whose teardown involves I/O can await it. Rust has no stable async Drop. The tracking issue for async drop codegen is still open and the feature is nightly-only, so today the workaround is an explicit async fn close(self) that callers must remember to call, which is exactly the IDisposable problem you came to Rust to escape. If your system is full of async resources that need graceful shutdown, this will annoy you.

And a fourth thing that is not a win for either side, just a note on proportion. For the large middle of application code, ownership is invisible. Integers, bool, small Copy structs, values that are created and consumed in one function: none of it triggers a single ownership decision. The rules only start costing you attention at the boundaries where data is shared, stored, or outlives the function that made it. That is a much smaller fraction of a codebase than week one suggests.

Checking yourself

Why can a type not implement both Copy and Drop? Copy means the compiler may duplicate the value implicitly, at any assignment, as often as it likes. A destructor that ran an unpredictable number of times on unpredictable duplicates would be meaningless, so the compiler rejects the combination with E0184.

Given a struct with a Drop impl, why can you not move one field out of it? Because the destructor normally takes &mut self at drop time and expects a fully initialized value; allowing a field to move out would let it observe a partially moved value. Rust's answer is to keep the struct whole and swap the field's contents out instead, with Option::take or mem::replace.

In the worked example, why is moved not dropped at the end of main even though it was declared there? Because it was moved into consume, which took ownership and dropped it at the end of its own body. The compiler's initialization analysis knows the binding is dead, so it emits no drop for it. If the move had been conditional, the compiler would have emitted a drop flag and a branch instead.

You get error[E0382]: borrow of moved value on a variable used inside a move closure and again afterwards. What are your three options, and which is usually right? Clone before the closure captures it, restructure so the closure borrows rather than moves, or wrap the value in Arc and clone the handle. For shared ownership across threads, Arc is often appropriate when the contained type satisfies the necessary thread-safety bounds; a value moved into one thread does not need Arc just for that transfer. For a value the closure merely reads once, borrowing is usually right, and cloning is the answer only when you actually want two independent values.

Get the next deep dive by email

New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.

You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.

Written by Zeeshan Adil

I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.