The error you're encountering is due to Rust's ownership rules. Let's break it down:
Error Explanation
-
The Issue:
The description parameter in add_task is of type String, which means it is moved into the function when add_task is called.
-
The Move:
Inside add_task, when you create a new Task instance:
let task = Task {
id: self.next_id,
description: description,
completed: false
};
The description is moved into the Task struct. After this, description is no longer valid in the scope of add_task because its value has been moved.
-
The Error:
When you try to print description afterwards:
println!("Task added : {}", description);
You're attempting to use description after it has been moved into the Task struct. This is not allowed in Rust, hence the error.
Fixing the Error
To fix this, you can simply print description before it gets moved into the Task struct:
fn add_task(&mut self, description: String) {
println!("Task added : {}", description); // Print before moving
let task = Task {
id: self.next_id,
description: description, // description is moved here
completed: false
};
self.tasks.push(task);
self.next_id += 1;
}
By printing description before creating the Task, you avoid using it after it has been moved.
Alternative: Cloning
If you need to use description after it's been moved (not necessary in this case but could be in other scenarios), you could clone it:
fn add_task(&mut self, description: String) {
let task = Task {
id: self.next_id,
description: description.clone(), // Clone description
completed: false
};
self.tasks.push(task);
self.next_id += 1;
println!("Task added : {}", description); // Now this is okay
}
However, cloning is generally less efficient than simply reordering your operations to avoid the issue.
Borrowing Instead of Moving
Another approach is to change add_task to borrow description instead of taking ownership:
fn add_task(&mut self, description: &str) {
let task = Task {
id: self.next_id,
description: description.to_string(), // Convert &str to String
completed: false
};
self.tasks.push(task);
self.next_id += 1;
println!("Task added : {}", description);
}
This way, description is not moved, and you can still use it after calling add_task. You would call add_task with a reference to a string slice (&str):
todo_list.add_task("Buy milk");
Or, if you have a String:
let task_desc = "Buy milk".to_string();
todo_list.add_task(&task_desc);
This approach is more flexible and avoids unnecessary cloning or moving.