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.
fn shout(s: String) -> String {
s.to_uppercase()
}
fn main() {
let name = String::from("ada");
let loud = shout(name);
println!("{loud} {name}");
}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.