Hello,
Unfortunately I didn't find any documentation on this subject.
So I have a pub type MyType = dyn Fn(...).
But when I write this:
pub fn some_func<F>(arg: F) where F: MyType {
...
}
Then I get: cannot find trait MyType in this scope.
MyType and some_func are in the same module.
Thank you very much in advance for any help.
In Rust, traits are not types and viceversa.
Thank your for your time and help.
Is there a way or workaround to achieve what I'm trying to do ?
Thank you for your help.
You could create your own trait, and use it as a bound:
trait MyFnTrait: Fn(usize) -> usize {}
impl<T: Fn(usize) -> usize> MyFnTrait for T {}
fn call_with_one<F>(func: F) -> usize
where F: MyFnTrait {
func(1)
}
fn main() {
let double = |x| x * 2;
assert_eq!(call_with_one(double), 2);
}
Thank you for your help.
Just to make sure I understand, wouldn't it be easier / better to write:
trait MyFnTrait: Fn(usize) -> usize {}
impl MyFnTrait for T {}
fn call_with_one<F>(func: F) -> usize
where F: MyFnTrait {
func(1)
}
fn main() {
let double = |x| x * 2;
assert_eq!(call_with_one(double), 2);
}
Or is there a reason for "repeating" Fn(usize) -> size in
impl<T: Fn(usize) -> usize> MyFnTrait for T {}
Thank you for your help.
As food for thought, you can try it in the playground:
Read the compilation error and it would help you to understand more than what I could write here.