Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting type T from Option<T>

Tags:

rust

I have some code generated by bindgen that has function pointers represented by Option<T>.

pub type SomeFnPointerType = ::std::option::Option<
  unsafe extern "C" fn ( /* .. large number of argument types .. */) 
    -> /* return type */
> ;

I want to store the unwrapped values in a structure. However, there are no type aliases for the inner function pointer types, so how can I define that structure? I cannot refactor the code because it's automatically generated.

I want to do something like this (in C++'ish pseudo code):

struct FunctionTable {
  decltype((None as SomeFnPointerType).unwrap()) unwrappedFn;
  /* ... */
};

or maybe just SomeFnPointerType::T if that is allowed.

Is it possible to achieve that in Rust? If not, the only way I see it is to manually define those types by copy-pasting code from the generated file into a separate handwritten file and keep the types in sync manually.

like image 201
RKS Avatar asked Dec 08 '18 07:12

RKS


1 Answers

You can define a trait that exposes the T as an associated type.

trait OptionExt {
    type Type;
}

impl<T> OptionExt for Option<T> {
    type Type = T;
}

type MyOption = Option<fn()>;

fn foo(f: <MyOption as OptionExt>::Type) {
    f();
}

fn main() {
    foo(|| {});
}
like image 153
Francis Gagné Avatar answered Sep 28 '22 07:09

Francis Gagné