Implement From trait for closure

Hello, I'm trying to implement the From trait for a closure:

pub enum Arg {
    Predicate(Box<dyn Fn() -> bool>)
}

impl From<Box<dyn Fn() -> bool>> for Arg {
    fn from(predicate: Box<dyn Fn() -> bool>) -> Self {
        Arg::Predicate(predicate)
    }
}

fn main() {
    Arg::from(Box::new(|| true));
}

Which produce the following error:

error[E0277]: the trait bound `Arg: From<Box<[closure@src/main.rs:13:24: 13:31]>>` is not satisfied
  --> src/main.rs:13:5
   |
13 |     Arg::from(Box::new(|| true));
   |     ^^^^^^^^^ the trait `From<Box<[closure@src/main.rs:13:24: 13:31]>>` is not implemented for `Arg`
   |
   = help: the following implementations were found:
             <Arg as From<Box<(dyn Fn() -> bool + 'static)>>>
   = note: required by `from`

Also, if possible I would like the Box in the main to not appear.
Thanks for the help.

You can do it with generics and trait bounds:

impl<T: 'static + Fn() -> bool> From<T> for Arg {
    fn from(predicate: T) -> Self {
        Arg::Predicate(Box::new(predicate))
    }
}

and then:

Arg::from(|| true);
3 Likes

Thanks a lot for this answer. Is it possible to have a version which does not involve a 'static lifetime?

Edit: ok I just found this post: Box with a trait object requires static lifetime? - #2 by Yandros which answer my question.

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.