Skip to content
Discussion options

You must be logged in to vote

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
  1. Borrow instead of move (preferred):
rustfn takes_reference(s: &String) {
    println!("{}", s);
}

takes_reference(&s);
println!("{}", s); // works fine
  1. Return ownership back:
r…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by cigscat
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants