genericsrusttype-parameter

Optional generic type Parameter for fn?


I would like a function to have an optional generic type Parameter to do something like this:

fn main() {
    bar::<()>();
}

fn bar<F: Foo>() {
    let x = some_computation();
    if F != () {
        let foo = F::new(x);
        foo.foo();
    }
}

trait Foo {
    fn new(x: u64) -> Self;
    fn foo(&self);
}

Is there a way to have an optional type parameter? And if so is there a way to check the type parameter for its presence inside the function?

I guess the answer is no, but is it possible to do that with macros then?


Solution

  • I know now! :D I can just provide a noop implementation of Foo:

    pub struct NoopFoo {}
    impl Foo for NoopFoo {
        fn new(_: u64) -> Self { NoopFoo {} }
        fn foo(&self) {}
    }
    

    I'm still curious if this could be solved with a macro though...