naim:
The enum
presented isn't actually meant to be for the programmer to write, It's just to show you what the compiler may emit.
enum FuncStates {
State1{ /* state data */ },
State2{ /* state data */ },
State3{ /* state data */ },
/* etc... */
}
You need to create a type that the compiler won't try to add to the imaginary enum (because if it does, it would be adding the enum to itself - which is not allowed).
enum States {
State1 {},
State2 { x: States }, // <- not allowed, compiler won't be able to find the size. It's infinite...
/* etc... */
}
It is possible to add indirection by adding an indirect type:
enum States {
State1 {},
State2 { x: Box<States> }, // this will compile, because a Box is a pointer.
}
Rust requires a Box
for this to be possible, and tokio's executor's spawn
function requires functions to be Pin
& Send
, this example complies with all these requirements:
naim:
fn handle_url(url: String) -> Pin<Box<dyn Future<Output=Result<(), ()>> + Send>> {
Box::pin(async move {
if url.len() <= 1 {
return Ok(());
}
let child_url = (&url[1..]).to_string();
tokio::spawn(handle_url(child_url));
Ok(())
})
}
Playground: Rust Playground
I understood that it is not meant to be written by programmer !!
But I am asking why the indirection is not broken by generating proper enum as I show above ?