Hi there,
I've been troubling over a struct that provides a new
function with a param that declares a function to do something. Here's my declarations:
pub struct MyStruct {
pub my_fn: Arc<
Box<dyn Fn() -> u32>
>,
}
impl MyStruct {
pub fn new<F>(my_fn: Arc<Box<F>>) -> MyStruct
where
F: Fn() -> MyStruct,
{
let _ = my_fn(); // Pretend this does something useful
MyStruct {
my_fn,
}
}
}
The compiler complains:
|
10 | pub fn new<F>(my_fn: Arc<Box<F>>) -> MyStruct
| - this type parameter
...
16 | my_fn,
| ^^^^^ expected trait object `dyn Fn`, found type parameter `F`
|
= note: expected struct `Arc<Box<(dyn Fn() -> u32 + 'static)>>`
found struct `Arc<Box<F>>`
= help: type parameters must be constrained to match other types
= note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters
If I remove Arc
from the above, then all is well. I suspect that the problem isn't anything to do with the problem being reported...
Here's the Rust Playground version: an example.
Any pointers? Thanks.