oop - Rust 中的对象和类

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

最佳答案

您需要添加一个明确的self 参数来生成methods :

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

没有显式 self 参数的函数被视为 associated functions ,无需特定实例即可调用。

关于oop - Rust 中的对象和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17304897/

相关文章:

java - 在类日志中存储学生评价的最佳方式

php - 使用 PHP 的 OOD 与基于功能服务的架构

rust - rsmpi 'mpi = 0.5.4'由于显然是拼写错误的函数调用而无法编译

http - 如何发送分块传输编码超响应?

oop - 类图——多个类使用同一个类

javascript - 在类方法中删除元素后无法过滤数组

objective-c - Objective-C - 如何实现自定义回调方法但强制执行特定参数?

rust - 向非引用类型添加生命周期约束

rust - 定义指向 C 不透明指针的字段的 Rust 习语是什么?

rust - 如何在 Rust 的内置函数上实现特征?