I'm trying to use a closure in a struct which makes it possible to implement a bunch of useful traits like From
.
In this case, I'd probably just end up using boxed closures, but is there some type magic I can do that would get it to work without using Box
?
struct Lazy<T, F: FnOnce() -> T> {
func: F,
}
impl<T, F: FnOnce() -> T> Lazy<T, F> {
fn evaluate(self) -> T {
(self.func)()
}
}
// This doesn't work :(
impl<T, F: FnOnce() -> T> From<T> for Lazy<T, F> {
fn from(value: T) -> Lazy<T, impl FnOnce() -> T> {
Lazy {
func: || value
}
}
}
// This works! But the ergonomics aren't as good as using
// Lazy::from or value.into()
fn from_value<T>(value: T) -> Lazy<T, impl FnOnce() -> T> {
Lazy {
func: || value
}
}
fn main() {
let value = from_value(10);
println!("Value is {}", value.evaluate());
// let value = Lazy::from(10);
// println!("Value is {}", value.evaluate());
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
--> src/main.rs:13:34
|
13 | fn from(value: T) -> Lazy<T, impl FnOnce() -> T> {
| ^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0562`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.