BuringStraw

BuringStraw

Error in Rust: Variables cannot be safely passed between threads when calling async functions

This is a pseudo code snippet

async fn a() {
    let a:T = ...;//T is a type that does not implement Send
    let b = foo(a);
    boo(b).await;
}

async fn boo() -> i32 {
    ...
}

In this case, there will be an error future cannot be sent between threads safely.
The solution is to ensure that a is dropped before await

async fn a() {
    let b;
    {
        let a:T = ...;//T is a type that does not implement Send
        b = foo(a);//Here, the extracted data is Sendable
    }
    boo(b).await;
}

However, manually dropping is not allowed

async fn a() {
    let a:T = ...;//T is a type that does not implement Send
    let b = foo(a);//Here, the extracted data is Sendable
    drop(a);//Compiler does not recognize
    boo(b).await;
}

For further explanation, please refer to https://blog.csdn.net/wangjun861205/article/details/118084436

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.