我正在摆弄 Rust,通过示例,尝试创建一个类。我一直在看 example of StatusLineText
它不断引发错误:
error: `self` is not available in a static method. Maybe a `self` argument is missing? [E0424]
self.id + self.extra
^~~~
error: no method named `get_total` found for type `main::Thing` in the current scope
println!("the thing's total is {}", my_thing.get_total());
^~~~~~~~~
我的代码很简单:
fn main() {
struct Thing {
id: i8,
extra: i8,
}
impl Thing {
pub fn new() -> Thing {
Thing { id: 3, extra: 2 }
}
pub fn get_total() -> i8 {
self.id + self.extra
}
}
let my_thing = Thing::new();
println!("the thing's total is {}", my_thing.get_total());
}
最佳答案
您需要添加一个明确的self
参数来生成methods :
fn get_total(&self) -> i8 {
self.id + self.extra
}
没有显式 self
参数的函数被视为 associated functions ,无需特定实例即可调用。
关于oop - Rust 中的对象和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17304897/