23

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

我的代码很简单:

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());
}
4

1 回答 1

26

您需要添加一个显式self参数来制作方法

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

没有显式self参数的函数被认为是关联函数,可以在没有特定实例的情况下调用。

于 2013-06-25T18:40:57.387 回答