Generic Structs with Rustler

The Problem

I have the following structs:

pub struct ExAfRef<T: HasAfEnum>(pub RwLock<Array<T>>);

#[derive(NifStruct)]
#[module = "ExAF.Backend"]
pub struct ExAf<T>
where
    T: HasAfEnum,
{
    pub resource: ResourceArc<ExAfRef<T>>,
}

On compiling it passes the following the error:

error[E0107]: missing generics for struct `datatypes::ExAf`
  --> src/datatypes.rs:10:12
   |
10 | pub struct ExAf<T>
   |            ^^^^ expected 1 generic argument
   |
note: struct defined here, with 1 generic parameter: `T`
  --> src/datatypes.rs:10:12
   |
10 | pub struct ExAf<T>
   |            ^^^^ -
help: add missing generic argument
   |
10 | pub struct ExAf<T><T>
   |            ~~~~~~~

However when I comment out / remove the rustler specific bits, I don’t have the error:

pub struct ExAfRef<T: HasAfEnum>(pub RwLock<Array<T>>);

pub struct ExAf<T>
where
    T: HasAfEnum,
{
    pub resource: ExAfRef<T>,
}

How can I use generic structs with rustler?

What I am trying to do

I am writing some bindings to arrayfire using their rust crate. Their Array struct is typed and support multiple types like i64 and f64. I am trying to access references (and create references) to Arrays from Elixir. I figured that writing a struct with a trait bound to support all the various types would be the best way to do it.

If there is a better way of doing this without a generic struct, I would be happy to implement it.

AFAIK, Rustler does not support generics for now.

1 Like