我正在摆弄Rust,通过示例,尝试上课.我一直在看这个例子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());
^~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
我的代码很简单:
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());
}
Run Code Online (Sandbox Code Playgroud)
Lee*_*Lee 25
您需要添加一个显式self参数来制作方法:
fn get_total(&self) -> i8 {
self.id + self.extra
}
Run Code Online (Sandbox Code Playgroud)
没有显式self参数的函数被认为是关联函数,可以在没有特定实例的情况下调用它们.
| 归档时间: |
|
| 查看次数: |
13981 次 |
| 最近记录: |