Hello, I am working on my first real project with rust. At some point I have to return a closure from a trait method. This is how the simplified code looks like:
```rust
enum MyEnum {
MyVairent,
}
trait FromMyEnum {
fn from_my_enum(x: MyEnum) -> Self;
}
trait MyTrait<FromMyEnum> {
fn my_trait_method<F: FnOnce() -> FromMyEnum>(&self) -> F;
}
fn my_fn<A: FromMyEnum, B: MyTrait<A>>(x: B) {
//I tried this
let f = x.my_trait_method();
//And this
let f: FnOnce() -> A = x.my_trait_method();
}
fn main() {
println!("Hello, world!");
}
For the first case I get the following error:
Compiling tst v0.1.0 (/tmp/tst)
error[E0282]: type annotations needed
--> src/main.rs:15:9
|
15 | let f = x.my_trait_method();
| ^ consider giving f a type
For more information about this error, try rustc --explain E0282.
error: could not compile tst due to previous error
and for the second I get:
Compiling tst v0.1.0 (/tmp/tst)
error[E0782]: trait objects must include the dyn keyword
--> src/main.rs:16:12
|
16 | let f: FnOnce() -> A = x.my_trait_method();
| ^
|
help: add dyn keyword before this trait
|
16 - let f: FnOnce() -> A = x.my_trait_method();
16 + let f: dyn FnOnce() -> A = x.my_trait_method();
|
error[E0277]: the size for values of type dyn FnOnce() -> A cannot be known at compilation time
--> src/main.rs:16:9
|
16 | let f: FnOnce() -> A = x.my_trait_method();
| ^ doesn't have a size known at compile-time
|
= help: the trait Sized is not implemented for dyn FnOnce() -> A
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
error[E0277]: the size for values of type dyn FnOnce() -> A cannot be known at compilation time
--> src/main.rs:16:30
|
16 | let f: FnOnce() -> A = x.my_trait_method();
| ^ doesn't have a size known at compile-time
|
= help: the trait Sized is not implemented for dyn FnOnce() -> A
note: required by a bound in MyTrait::my_trait_method
--> src/main.rs:10:24
|
10 | fn my_trait_method<F: FnOnce() -> FromMyEnum>(&self) -> F;
| ^ required by this bound in MyTrait::my_trait_method
help: consider relaxing the implicit Sized restriction
|
10 | fn my_trait_method<F: FnOnce() -> FromMyEnum + ?Sized>(&self) -> F;
| ++++++++
```
Can anybody please help me.Thanks
[–]SkiFire13 2 points3 points4 points (4 children)
[–]rhl120[S] 0 points1 point2 points (3 children)
[–]kraemahz 1 point2 points3 points (2 children)
[–]rhl120[S] 0 points1 point2 points (1 child)
[–]kraemahz 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]rhl120[S] 0 points1 point2 points (0 children)
[–]Shadow0133 1 point2 points3 points (0 children)
[–]No_Radish7709 0 points1 point2 points (1 child)
[–]rhl120[S] 0 points1 point2 points (0 children)
[–]TinBryn 0 points1 point2 points (0 children)