Function pointer with param of type using impl
Would something like this work, using either a type with a trait, or by an unstable feature trait_alias?
#![feature(trait_alias)]
pub trait IoContext {}
struct MyContext {}
impl IoContext for MyContext {}
pub fn do_thing_with_context(
context: &mut impl IoContext,
) -> () {
()
}
pub trait MyFuncRefTraitAlias<IO> = Fn(&mut IO) ;
fn use_fn_ref_trait_alias<F: MyFuncRefTraitAlias<IO>, IO: IoContext>(context: &mut IO, f: F) {
f(context)
}
pub type MyFuncRefTyped<IO> = fn(&mut IO);
fn use_fn_ref_typed<IO: IoContext>(context: &mut IO, f: MyFuncRefTyped<IO>) {
f(context)
}
fn main() {
let mut context = MyContext {};
let fn_ref = do_thing_with_context;
use_fn_ref_trait_alias(&mut context, fn_ref);
use_fn_ref_typed(&mut context, fn_ref);
}
Note that you can not use type alias bounds in this case for IO
or F
(e.g. type MyFuncRef<IO: IoContext, F>
), see https://doc.rust-lang.org/stable/nightly-rustc/rustc_lint/builtin/static.TYPE_ALIAS_BOUNDS.html