Rust, what decides a function name is a fn pointer to fn item?

44 Views Asked by At

Here is the code that works.

use core::future::Future;

async fn haha(ctx: u8) -> u8 {
    return 2u8;
}

fn set_func<T>(path: &'static str, f: fn(u8) -> T) -> u8
where
    T: Future<Output = u8> + Send + 'static,
{
    return 8u8;
}

fn main() {
  set_func("haha", haha);
}

but when I change the haha function to

use core::future::Future;

async fn haha(ctx: &mut u8) -> u8 {
    return 2u8;
}

fn set_func<T>(path: &'static str, f: fn(&mut u8) -> T) -> u8
where
    T: Future<Output = u8> + Send + 'static,
{
    return 8u8;
}

fn main() {
  set_func("haha", haha);
}

Then error will shows like this:

   |
13 |     set_func("haha", haha);
   |     --------         ^^^^ one type is more general than the other
   |     |
   |     arguments to this function are incorrect
   |
   = note: expected fn pointer `for<'a> fn(&'a mut u8) -> _`
                 found fn item `for<'a> fn(&'a mut u8) -> impl Future<Output = u8> {haha}`

I am so confusing that changing a argument from u8 to &mut u8 will change the fn pointer to fn item. why this happen?
and the &mut u8 is a requirement, do you have anyway can keep the &mut u8 and make it pass the type check?

0

There are 0 best solutions below