compiler/rustc_error_codes/src/error_codes/E0504.md MARKDOWN 104 lines View on github.com → Search inside
1#### Note: this error code is no longer emitted by the compiler.23This error occurs when an attempt is made to move a borrowed variable into a4closure.56Erroneous code example:78```compile_fail9struct FancyNum {10    num: u8,11}1213fn main() {14    let fancy_num = FancyNum { num: 5 };15    let fancy_ref = &fancy_num;1617    let x = move || {18        println!("child function: {}", fancy_num.num);19        // error: cannot move `fancy_num` into closure because it is borrowed20    };2122    x();23    println!("main function: {}", fancy_ref.num);24}25```2627Here, `fancy_num` is borrowed by `fancy_ref` and so cannot be moved into28the closure `x`. There is no way to move a value into a closure while it is29borrowed, as that would invalidate the borrow.3031If the closure can't outlive the value being moved, try using a reference32rather than moving:3334```35struct FancyNum {36    num: u8,37}3839fn main() {40    let fancy_num = FancyNum { num: 5 };41    let fancy_ref = &fancy_num;4243    let x = move || {44        // fancy_ref is usable here because it doesn't move `fancy_num`45        println!("child function: {}", fancy_ref.num);46    };4748    x();4950    println!("main function: {}", fancy_num.num);51}52```5354If the value has to be borrowed and then moved, try limiting the lifetime of55the borrow using a scoped block:5657```58struct FancyNum {59    num: u8,60}6162fn main() {63    let fancy_num = FancyNum { num: 5 };6465    {66        let fancy_ref = &fancy_num;67        println!("main function: {}", fancy_ref.num);68        // `fancy_ref` goes out of scope here69    }7071    let x = move || {72        // `fancy_num` can be moved now (no more references exist)73        println!("child function: {}", fancy_num.num);74    };7576    x();77}78```7980If the lifetime of a reference isn't enough, such as in the case of threading,81consider using an `Arc` to create a reference-counted value:8283```84use std::sync::Arc;85use std::thread;8687struct FancyNum {88    num: u8,89}9091fn main() {92    let fancy_ref1 = Arc::new(FancyNum { num: 5 });93    let fancy_ref2 = fancy_ref1.clone();9495    let x = thread::spawn(move || {96        // `fancy_ref1` can be moved and has a `'static` lifetime97        println!("child thread: {}", fancy_ref1.num);98    });99100    x.join().expect("child thread should finish");101    println!("main thread: {}", fancy_ref2.num);102}103```

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.