我正在编写一个非常简单的 getter/setting 模型,我想开始在 Rust 中使用它,出于简单性的原因,我将使用 struct
和 impl
。
struct Person {
firstName: String,
lastName: String,
}
impl Person {
fn get_first_name(&mut self) -> String { return self.firstName; }
fn get_last_name(&mut self) -> String { return self.lastName; }
fn set_first_name(&mut self, x: String) { self.firstName = x; }
fn set_last_name(&mut self, x: String) { self.lastName = x; }
fn default() -> Person {
Person {firstName: "".to_string(), lastName: "".to_string()}
}
}
fn main() {
let mut my_person : Person = Person{ ..Person::default() };
my_person.set_first_name("John".to_string());
my_person.set_last_name("Doe".to_string());
println!("{}", my_person.firstName);
println!("{}", my_person.lastName);
}
运行这段代码时,我得到了以下错误。
src\main.rs:7:53: 7:57 error: cannot move out of borrowed content [E0507]
src\main.rs:7 fn get_first_name(&mut self) -> String { return self.firstName; }
^~~~
src\main.rs:8:53: 8:57 error: cannot move out of borrowed content [E0507]
src\main.rs:8 fn get_last_name(&mut self) -> String { return self.lastName; }
^~~~
error: aborting due to 2 previous errors
Could not compile `sandbox`.
由于我对 Rust 很陌生,请问有人能指出我的错误吗?
如果有更好的写法建议,也欢迎提供。我一直在寻找更易读、更快速的方法。
struct Person { pub first_name: String, pub last_name: String, }
呢? - Matthieu M.