我有一个用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...')
答案 0 :(得分:1)
您提供的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
,其方法将位于{{1 }}块。)如果该答案更接近您要查找的内容,我可以对其进行编辑。