Rust中的对象和类

时间:2013-06-25 18:30:33

标签: oop rust

我正在摆弄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());
}

1 个答案:

答案 0 :(得分:25)

您需要添加明确的self参数才能生成methods

fn get_total(&self) -> i8 {
    self.id + self.extra
}

没有显式self参数的函数被视为associated functions,可以在没有特定实例的情况下调用它。