5

I've got a problem a bit more complicated than this. But I think this breaks it down. I have some generic struct, which has three constructors to get a concrete typed struct. They all have the same generic methods, except for the constructors. What I want is something like this:

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![] }
    }
}

When I try to compile this. pyo3 warns me that it cannot use generics. error: #[pyclass] cannot have generic parameters.

Is it possible to create some sort of generic base class from which the concrete types inherit?.

For completion; here is my Cargo.toml:

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

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

[lib]
name = "example"
crate-type = ["cdylib"]
ritchie46
  • 10,405
  • 1
  • 24
  • 43
  • if `AnyVec` is to be used in python, it should contain a `Vec` rather than `Vec`. Also you need to implement [`PyGCProtocol`](https://pyo3.rs/v0.9.0-alpha.1/class.html#garbage-collector-integration). – charlieh_7 Mar 14 '20 at 04:08
  • 1
    Hmm.. Maybe it isn't the best example. Those Generic types are not python types. But Rust types. I've got a generic wrapper class which can be made concrete by 4 different structs which implement the same trait. – ritchie46 Mar 14 '20 at 12:42

0 Answers0