Skip to content

Generic Rust Struct Exposed by Pyo3 #2660

Discussion options

You must be logged in to vote

If the set of relevant types is closed, you could put an enum inside the #[pyclass], e.g.

#[pyclass]
pub struct Wrapper {
  inner: WrapperInner,
}

#[pymethods]
impl Wrapper {
  pub fn a(&self) {
    match self.inner {
      WrapperInner::Int(inner) => inner.a(),
      WrapperInner::Float(inner) => inner.a(),
      WrapperInner::Str(inner) => inner.a(),
    }
  }
}

enum WrapperInner {
  Int(Core<i64>),
  Float(Core<f64>),
  Str(Core<String>),
}

If the set is open, you can try to put a trait object within the #[pyclass], e.g.

#[pyclass]
pub struct Wrapper {
  inner: Box<dyn WrapperInner>,
}

#[pymethods]
impl Wrapper {
  pub fn a(&self) {
    self.inner.a();
  }
}

trait WrapperInner {
  fn 

Replies: 1 comment 8 replies

Comment options

You must be logged in to vote
8 replies
@StuartHadfield
Comment options

@adamreichold
Comment options

@StuartHadfield
Comment options

@mejrs
Comment options

mejrs Oct 7, 2022
Collaborator

@StuartHadfield
Comment options

Answer selected by StuartHadfield
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants