0

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?

3
  • You mean your trait has a function new() that you want to call in your fun()? Commented Nov 21, 2020 at 15:45
  • 1
    Your question is really confusing to me at least. As far as I understand, you can achieve this as fn func<T: MyTrait>(arg: T){let state = T::new();} Commented Nov 21, 2020 at 15:52
  • Yes, and there is high chance as soon as it stops to be confusing, I find the answer. :-. Anyway, I want to pass the type of the structure into the function. arg: T is a function here, and I want to pass the type to use. Commented Nov 21, 2020 at 16:23

1 Answer 1

3

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>();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, yes, you are totally right! I was under impression I MUST to write something inside (...), but yes, it's here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.