Search code examples
functionrustasync-awaitclosuresfunction-pointers

Can I write rust code equivalent to the typescript code below?


Here is the typescript code:

function gen(msg: string): () => Promise<void> {
    return async function() {
        // await any async function here ...
        await sleep(1000);
        console.log(msg);
    }
}

Literally translated into rust:

fn gen(msg: String) -> async fn() -> () {
    async || {
        sleep(1000).await;
        println!("{}", msg);
    }
}

But the compiler does not allow such sentence.


Solution

  • A possible (and correct) translation will be:

    use std::future::Future;
    use std::pin::Pin;
    
    fn gen(msg: String) -> impl Fn() -> Pin<Box<dyn Future<Output = ()>>> {
        move || {
            let msg = msg.clone();
            Box::pin(async move {
                sleep(1000).await;
                println!("{}", msg);
            })
        }
    }
    

    But it is not necessarily the best. Rust is not TypeScript, and translating code literally isn't going to work.