made in gimp, with <3

Context for actual rust programmers

I was having massive beef with the rust compiler yesterday, every cargo check takes 20 seconds.

And then look at the three functions below, only one of them are Send, if you know why, please let me know.

(Note: value that is not Send cannot be held across an await point, and Box<dyn Error> is not Send)

async fn one() {
    let res: Result<(), Box<dyn Error>> = do_stuff();
    if let Err(err) = res {
        let content = err.to_string();
        let _ = do_stuff(content).await;
    }
}

async fn two() {
    let res: Result<(), Box<dyn Error>> = do_stuff();
    let content = if let Err(err) = res {
        Some(err.to_string())
    } else {
        None
    };
    drop(res);
    if let Some(content) = content {
        let _ = do_stuff(content).await;
    }
}

async fn three() {
    let content = {
        let res: Result<(), Box<dyn Error>> = do_stuff();
        if let Err(err) = res {
            Some(err.to_string())
        } else {
            None
        }
    };
    if let Some(content) = content {
        let _ = do_stuff(content).await;
    }
}
  • wisha@lemmy.ml
    link
    fedilink
    arrow-up
    5
    ·
    edit-2
    5 hours ago

    You are running into the Send Approximation being too conservative. The compiler does not like to see a let binding for a non-Send type and an .await statement in the same scope. It is not (yet) smart enough to know that the non-Send type is already consumed by the time of the .await.

    You’ve already discovered the workaround in your three(). To make it more concise

    async fn four() {
        let content = do_stuff().err().map(|err| err.to_string());
        if let Some(content) = content {
            let _ = do_stuff_2(content).await;
        }
    }