Repository navigation
Why does the borrow checker complain when I try to use a variable after passing it to a function? #2406
|
I'm doing the rustlings exercises and I keep running into this error: |
Replies: 2 comments
|
This is Rust's ownership system at work. When you pass a variable to a function, ownership moves into that function and the original variable is no longer valid: rustfn takes_ownership(s: String) {
println!("{}", s);
} // s is dropped here
fn main() {
let s = String::from("hello");
takes_ownership(s);
println!("{}", s); // error! s was moved
}```
You have three ways to fix it:
1. Clone the value (simplest but has a cost):
```rust
rusttakes_ownership(s.clone());
println!("{}", s); // works fine
rustfn takes_reference(s: &String) {
println!("{}", s);
}
takes_reference(&s);
println!("{}", s); // works fine
rustfn takes_and_returns(s: String) -> String {
println!("{}", s);
s // give it back
}
let s = takes_and_returns(s);
println!("{}", s); // works fineIn most cases borrowing (&) is the idiomatic Rust solution. Types that implement Copy like i32, bool, f64 don't have this problem since they're copied automatically instead of moved. |
|
@cigscat consider reading the chapter on ownership of the Rust book. It explains these concepts in great detail. Understanding them is essential for becoming a productive and confident Rust programmer. https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html |
This is Rust's ownership system at work. When you pass a variable to a function, ownership moves into that function and the original variable is no longer valid: