Generic Function Pointers

I'm trying to create a function that takes an optional function pointer (that returns a generic), and returns either that function pointer or a default function pointer that has the same inputs and outputs. Here is my code, but as you'll see, my default function doesn't work because it won't return the generic.

fn create_function<B>(function: Option<fn(f32) -> B>) -> fn(f32) -> B {
    function.unwrap_or(|f| {f <- Error here})
}

Is there a way around this? I was thinking of potentially using a macro, but I'm not sure if that's necessary.

How do you expect to return B? This requirement looks like a logic error: the type is chosen by the caller, and it could be anything. I can call create_function::<ClownCar>(None) and this code would have no way of knowing how to create an instance of this type,

Not returning anything works:

fn create_function<B>(function: Option<fn(f32) -> B>) -> fn(f32) -> B {
    function.unwrap_or(|_| panic!())
}

You could also require something like B: Default and return the B::default() value.

Well if the function passed in is None, than I want to specify my own B, because the caller didn't specify it. But I guess it is possible for the caller to specify it without passing a function in, so I guess that can't be done?

You're returning a function that returns B, so you can't just ignore the B type, and return something else like fn(f32) -> i32.

None is not like null. It is strongly typed. None of i32 is incompatible with None of B, etc.

You could require e.g. B: From<i32> and then return B::from(0) for example. Or you could change the return type to be fn(f32) -> Option<B> and return a function that returns None.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.