Error

"use of moved value" — What It Means and How to Fix It

Fix the 'use of moved value' error in Rust by cloning the data or passing a reference instead of moving ownership.

The error "use of moved value" means you tried to use a variable after its ownership was transferred to another location. In Rust, types like String move rather than copy when assigned or passed to functions, invalidating the original variable. To fix this, pass a reference (&) instead of the value, or clone the data if you need a second owner.

fn takes_ownership(some_string: String) {
    println!("{some_string}");
}

fn main() {
    let s1 = String::from("hello");
    // Pass a reference instead of moving the value
    takes_ownership(s1.clone()); 
    // s1 is still valid here because we cloned it
    println!("{s1}");
}