FAQ - Help and questions

How do I fix "borrow of moved value" and "use of moved value" (E0382)?

#errors#ownership#borrowingpublished 3 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

A value was moved into a function, a variable or a closure, so the original name is no longer valid. Lend the value with & instead of giving it away, clone it when two owners are really needed, or change the function to return the value. The compiler marks where the move happened.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Passing a String (or any type that is not Copy) to a function by value hands ownership to that function. The caller's variable is then empty as far as the compiler is concerned. The message marks the line where the variable was created, the line where it moved, and the line where you used it afterwards.

src/main.rsrust
fn shout(s: String) -> String {
    s.to_uppercase()
}

fn main() {
    let name = String::from("ada");
    let loud = shout(name);
    println!("{loud} {name}");
}
text
error[E0382]: borrow of moved value: `name`
 --> src/main.rs:8:23
  |
6 |     let name = String::from("ada");
  |         ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
7 |     let loud = shout(name);
  |                      ---- value moved here
8 |     println!("{loud} {name}");
  |                       ^^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `shout` to borrow instead if owning the value isn't necessary
 --> src/main.rs:1:13
  |
1 | fn shout(s: String) -> String {
  |    -----    ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
  |
7 |     let loud = shout(name.clone());
  |                          ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0382`.

The answers below are the usual fixes.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    3 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    Approach 1: lend it with a reference#

    If the function only needs to read, change its parameter to &str (or &String, &[T]) and pass &name. Nothing is copied and the caller keeps the value.

    src/main.rsrust
    fn shout(s: &str) -> String {
        s.to_uppercase()
    }
    
    fn main() {
        let name = String::from("ada");
        let loud = shout(&name); // lend it instead of giving it away
        println!("{loud} {name}");
    }
    text
    ADA ada
      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      Approach 2: clone before the move#

      If the function must own its input, call it with shout(name.clone()) and keep the original. This copies the text, so avoid it in hot loops.

        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail
        #4

        Approach 3: give the value back#

        If the function takes ownership, uses the value and could return it (or a changed version), return it and rebind: let name = process(name);. This fits "transform" style functions.

        Common mistakes#

        • Moving a value inside a loop: for _ in 0..3 { consume(name); } moves it on the first round. Pass &name, or clone.
        • Using a variable after move || closed over it. The closure owns it.
        • Matching on an Option<String> field with match opt { Some(s) => ... } and then using opt. Match on &opt or use opt.as_ref().

        See also the thread on move, Copy and Clone.

          QuoteReply
          Share
          Hacker NewsRedditLinkedInE-mail