oop - Rust 的正确 OOP 架构是什么?

标签 oop rust

<分区>

我有一个用 python 编写并使用类的程序。 我想将相同的结构转换为 Rust,但我们没有 Rust 中的类,而是我们有 (impl & strcut)。所以这让我感到困惑,如何在 Rust 中实现与 python 相同的 OOP 结构!

请提供一个 Rust 架构的示例,以便我可以将其作为引用。

我试过阅读本教程,但没有得到我想要的。 https://stevedonovan.github.io/rust-gentle-intro/object-orientation.html

我现有的程序示例:

文件:main.py

import my_lib

class main(object):
    def __init__(self):
        print('main > init')

    def start(self):
        my_lib.run()


if __name__ == "__main__":
    main()

文件:/lib/my_lib.py

    def run():
        print('running...')

最佳答案

您提供的 python 代码示例没有使用很多面向对象的功能,但翻译成 Rust 并不难:

文件:main.rs

mod my_lib; // This instructs Rust to look for `my_lib.rs` and import it as `my_lib`.
mod main {
    pub fn init() {
        println!("main > init");
    }

    pub fn start() {
        super::my_lib::run() // We have to add super:: to talk about things that were imported in the parent module rather than the `main` module itself, like `my_lib` 
    }
}

fn main() { // This is the function that starts your program. It's always called `main`.
    main::init()
}

文件:my_lib.rs

pub fn run() {
    println!("running...")
}

值得注意的是,这并不完全等同于您的 python 代码,因为 main 是一个模块而不是一个类。如果您打算使用它的 self 实例来存储数据或任何持久状态,则该示例看起来会有所不同(main 将是一个 struct,并且它的方法将在 impl block 中。)如果这更接近您正在寻找的内容,我可以编辑我的答案。

关于oop - Rust 的正确 OOP 架构是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56183016/

相关文章:

javascript - 我应该如何处理 JavaScript 中对象构造函数的无效输入

rust - rust 生命周期参数必须超过静态生命周期

java - Java模拟医院(优先队列)

java - 私有(private)变量内部类 : explanation of value?

c# - 如何从程序集中只公开一个特定的类?

rust - 调用 Option::map 后如何使用值?

rust - 如何创建以特征作为参数的setter

c++ - 无法从其他类的函数访问对象的参数

rust - 如何从 Rust 链接 gtk?

rust - 如何查看 TcpStream 并阻塞直到有足够的字节可用?