我有一个用 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 中。)如果这更接近您正在寻找的内容,我可以编辑我的答案。