How to return default for generic

pub struct Handler<F> where F: Fn(&str) -> &str {
    pub func: F,
}

How to implement Default?
How to make function

fn foo(s: &str) -> &str {}

fn default_handler() -> ? {
    Handler { func: foo }
}

Also I tried

pub struct Handler {
    pub request_access_token: &'static (Fn(&str) -> AccessTokenRequestResponse + Send + Sync),
}

impl Default for Handler {
    fn default() -> Self {
        Handler {
            request_access_token: &request_access_token as &'static (Fn(&str) -> AccessTokenRequestResponse + Send + Sync),
        }
    }
}

This does not work neither.

You can either use boxed closures:

pub struct Handler {
    pub func: Box<Fn(&str) -> &str>,
}

impl Default for Handler {
    fn default() -> Handler {
        Handler {
            func: Box::new(|x| x)
        }
    }
}

or, if you don't need closures, bare fn pointers which are not traits:

pub struct Handler {
    pub func: fn(&str) -> &str,
}

fn default_func(x: &str) -> &str { x }

impl Default for Handler {
    fn default() -> Handler {
        Handler {
            func: default_func
        }
    }
}
1 Like

Where can I find difference between fn and Fn?

Good question. In the book, there is some info in sections 4.2 (fn) and 4.23 (Fn).

Basically, fn types are function pointers that don't carry around captured closure environments, so they are Sized. Fn are a family of traits (one for every argument/return type combination) that are implemented by closures (and normal functions).

1 Like