Rust Pyo3 绑定:如何在通用 Rust 类型上重用 Python 方法

rit*_*e46 6 python rust pyo3

我有一个比这个更复杂的问题。但我认为这打破了它。我有一些通用结构,它具有三个构造函数来获取具体类型的结构。除了构造函数之外,它们都具有相同的通用方法。我想要的是这样的:

use pyo3::prelude::*;

#[pyclass]
struct AnyVec<T> {
    vec_: Vec<T>,
}

// General methods which
#[pymethods]
impl<T> AnyVec<T> {
    fn push(&mut self, v: T) {
        self.vec_.push(v)
    }

    fn pop(&mut self, v: T) -> T {
        self.vec_.pop()
    }
}

#[pymethods]
impl AnyVec<String> {
    #[new]
    fn new() -> Self {
        AnyVec { vec_: vec![] }
    }
}

#[pymethods]
impl AnyVec<f32> {
    #[new]
    fn new() -> Self {
        AnyVec { vec_: vec![] }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译这个时。pyo3警告我它不能使用泛型。error: #[pyclass] cannot have generic parameters

是否可以创建某种通用基础class来继承具体类型?

为了完成;这是我的Cargo.toml

[package]
name = "example"
edition = "2018"

[dependencies]
pyo3 = { version="0.9.0-alpha.1", features = ["extension-module"] }

[lib]
name = "example"
crate-type = ["cdylib"]
Run Code Online (Sandbox Code Playgroud)