George Shuklin
George Shuklin

Reputation: 7867

How to request and use a struct (without a struct instance!) inside a generic function?

I have this code:

fn func<T, U>(f: T) where T: Fn()-> U, U: MyTrait {
    let state = f();
    // ...
}

f here is just a new function from a trait MyTrait for some struct. I want to have a function which works with every struct implementing MyTrait, and there is new method for that trait I want to call for state.

How can I pass the struct (not a value with type of that struct) into a function with restriction on the specific trait been implemented for that struct?

Upvotes: 0

Views: 301

Answers (1)

Kevin Reid
Kevin Reid

Reputation: 43733

You do not need to pass any parameter; the type parameter U you already have is all you need.

fn func<U>(...)
where 
   U: MyTrait
{
    ...
    let state = U::new();
    ...
}

Or did you mean you want a generic implementation of just Fn() -> U? That's even easier: U::new is already that. Example using Default as the trait, but you can use any trait in the same way:

use std::fmt::Debug;

fn print_instance<T: Debug, F: Fn() -> T>(f: F) {
    println!("{:?}", f());
}

fn print_default<T: Debug + Default>() {
    print_instance::<T, _>(Default::default);
}

fn main() {
    print_default::<Vec<i32>>();
    print_default::<f32>();
}

Upvotes: 3

Related Questions