我正在使用Rust构建一个简单的命令行待办事项应用程序。如果我不实现复制特性,则会出现以下错误:"move occurs because 'todo' has type 'todo::Todo', which does not implement the 'Copy' trait"。当我尝试为我的Todo结构实现Copy特性时,我收到以下错误消息:"field text: String does not implement the Copy trait"。如何修复此错误?以下是我的代码:
pub type todo_type = Vec<Todo>;
#[derive(Copy)]
pub struct Todo {
id: usize,
text: String,
completed: bool,
}
impl Todo {
pub fn new(text: String, id: usize) -> Todo {
Todo {
text,
id,
completed: false,
}
}
}
pub struct Todos {
todos: todo_type,
}
impl Todos {
pub fn new(todos: todo_type) -> Todos {
Todos { todos }
}
pub fn get_all_todos(self) -> todo_type {
self.todos
}
pub fn get_single_todo(self, todo_index: usize) -> Todo {
unimplemented!()
}
pub fn add_todo(self, text: String) -> Todo {
let id: usize = 1;
if self.todos.len() == 0 {
let id = 1;
} else {
let last_todo = match self.todos.len() {
0 => None,
n => Some(&self.todos[n - 1]),
};
let id = last_todo.unwrap().id;
}
let todo = Todo::new(text, id);
self.todos.push(todo);
todo
}
pub fn remove_todo(self, todo_index: usize) -> bool {
self.todos.remove(todo_index);
true
}
}
#[derive(Clone)]
来派生Clone
,这将使你的结构体提供clone()
函数。 - Michael Andersonadd_todo
返回Todo
,以及为什么您需要在Todos
上的每个单独方法都消耗self
? - CerberusTodo
。你有什么想法来解决这个错误:“无法将self.todos
借为可变的,因为self
没有声明为可变的”? - Henry Boisdequinself
替换为mut self
来修复它。 - Henry Boisdequin