Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it idiomatic to use `impl<T> From<T> for Option<T>` in argument position?

Tags:

rust

This trait is implemented since 1.12.0:

impl<T> From<T> for Option<T> {
    fn from(val: T) -> Option<T> {
        Some(val)
    }
}

How idiomatic is this as an argument? Consider this example:

fn do_things(parameters: &Foo, optional_argument: impl Into<Option<Duration>>) {
    let optional_argument = optional_argument.into();
    // use it...
}

If you see the documentation, it's (more or less) clear (if you know, that this trait is implemented). But if you see the code, you may be confused:

do_things(params, Duration::from_millis(100));

Is this fine to use or should it be avoided?

like image 607
Tim Diekmann Avatar asked Aug 16 '18 22:08

Tim Diekmann


1 Answers

This pattern is uncommon, but reasonably easy to understand. If it's convenient in the context of your library's usage, it should be OK.

I think it's more common to have do_stuff and do_stuff_with_timeout functions.

like image 158
Kornel Avatar answered Nov 06 '22 19:11

Kornel