小编the*_*eth的帖子

如何使用 PyO3 从 Python 访问 Rust 迭代器?

我对 Rust 很陌生,我的第一个“严肃”项目涉及使用 PyO3 为小型 Rust 库编写 Python 包装器。这主要是非常轻松的,但我正在努力研究如何将 Rust 上Vec的惰性迭代器暴露给 Python 代码。

到目前为止,我一直在收集迭代器产生的值并返回一个列表,这显然不是最好的解决方案。这是一些说明我的问题的代码:

use pyo3::prelude::*;

// The Rust Iterator, from the library I'm wrapping.
pub struct RustIterator<'a> {
    position: usize,
    view: &'a Vec<isize>
}

impl<'a> Iterator for RustIterator<'a> {
    type Item = &'a isize;

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.view.get(self.position);
        if let Some(_) = result { self.position += 1 };
        result
    }
}

// The Rust struct, from the library I'm wrapping.
struct …
Run Code Online (Sandbox Code Playgroud)

python iterator rust pyo3

8
推荐指数
1
解决办法
291
查看次数

标签 统计

iterator ×1

pyo3 ×1

python ×1

rust ×1