Accept uninstantiated struct as func parameter

Hi Dear Community,

I got some structs which impled Marker Trait, which got the same associated function test().
Is it possible to make a function accept uninstantiated struct as parameter?
So that I can call T::test() directly without instantiation.
like

// this works but bar should be instantiated struct instance. 
fn Foo(bar: T) -> String 
where T: Marker {
    T::test()
}

trait Marker: Sized {
    fn test() -> String;
}

Or any other way I can achieve similar result?

You have to define the generic parameter T in Foo, adding the Marker trait bound to it. Then you can call the associated function:

fn Foo<T: Marker>() -> String {
    T::test()
}

trait Marker: Sized {
    fn test() -> String;
}
2 Likes

The original code already had a where clause that will do the same thing right?

I think this is a type inference problem. How does foo know what concrete type of T to monomorphize to? The parameter wal doing that in the original code.

I think this is a case for the turbo fish. Assuming you have some struct Bar that is Marker, then you would do something like this: foo::<Bar>(). Rustc can then figure out exactly what type it needs to monomorphize.

Yep. When the compiler has no other information it can use to infer the type parameter you'll need to supply it yourself using turbofish.

1 Like

The original code didn't have a generic parameter, T was referring to some type named exactly T.

2 Likes

Oh yeah, I totally missed that, distracted by the where clause I guess.

Thanks a lot!