Rust Async Programming async/await
In modern programming, asynchronous programming is becoming increasingly important because it allows programs to remain unblocked while waiting for I/O operations (such as file reads/writes, network communication, etc.), thereby improving performance and responsiveness.
Asynchronous programming is a way to handle non-blocking operations in Rust, allowing a program to remain unblocked while performing long I/O operations, and to execute other tasks while waiting.
Rust provides a variety of tools and libraries for asynchronous programming, including the async and await keywords, futures, and async runtimes (such as tokio, async-std, etc.), as well as other auxiliary tools.
-
Future: Future is an abstraction in Rust representing an asynchronous operation. It is a computation that may not have completed yet, and will return a value or an error at some point in the future.
-
async/await:
asyncThe keyword is used to define an async function, which returns a Future.awaitThe keyword is used to suspend the execution of the current Future until it completes.
Example
The following example shows how to use the async and await keywords to write an async function, and how to execute an async task within an async function and wait for its completion.
Example
// Import the required dependency libraries
use
tokio
;
use
tokio
::
time
::
{
self
,
Duration
}
;
// Async function, simulating an async task
async
fn
async_task
(
)
->
u32
{
// Simulate an async operation, waiting for 1 second
time
::
sleep
(
Duration
::
from_secs
(
1
)
)
.await
;
// Return the result
42
}
// Async task execution function
async
fn
execute_async_task
(
)
{
// Call the async task and wait for its completion
let
result
=
async_task
(
)
.await
;
// Output result
println
!
(
"Async task result: {}"
,
result
)
;
}
// Main function
[
tokio
::
main
]
async
fn
main
(
)
{
println
!
(
"Start executing async task..."
)
;
// Call the async task execution function and wait for its completion
execute_async_task
(
)
.await
;
println
!
(
"Async task completed!"
)
;
}
In the above code, we first defined an async function async_task()which simulates an async operation, using the tokio::time::delay_for() method to wait for 1 second, then returns the result 42. Then we defined an async task execution function execute_async_task()in which we call the async function, and use the await keyword to wait for the async task to complete. Finally, in the main used in the function tokio::main macro to run the async task execution function and wait for its completion.
Running this program, you can see it outputs a message indicating the start of the async task, then after waiting 1 second outputs the result of the async task, and finally outputs a message indicating the async task is complete:
Start executing async task...
Async task result: 42
Async task completed!
This example demonstrates using in Rust the async and await keyword to write async functions, and how to execute async tasks within an async function and wait for their completion.
The following example uses the tokio library to perform an asynchronous HTTP request and output the response result:
Example 2
// Import the required dependency libraries
use
std
::
error
::
Error
;
use
tokio
::
runtime
::
Runtime
;
use
reqwest
::
get
;
// Async function for performing an HTTP GET request and returning the response result
async
fn
fetch_url
(
url
:
&
str
)
->
Result
<
String
,
Box
<dyn Error
{
// Use reqwest to initiate an async HTTP GET request
let
response
=
get
(
url
)
.await?
;
let
body
=
response.text
(
)
.await?
;
Ok
(
body
)
}
// Async task execution function
async
fn
execute_async_task
(
)
->
Result
<
(
)
,
Box
<dyn Error
{
// Initiate an async HTTP request
let
url
=
"https://jsonplaceholder.typicode.com/posts/1"
;
let
result
=
fetch_url
(
url
)
.await?
;
// Output the response result
println
!
(
"Response: {}"
,
result
)
;
Ok
(
(
)
)
}
// Main function
fn
main
(
)
{
// Create an async runtime
let
rt
=
Runtime
::
new
(
)
.unwrap
(
)
;
// Execute the async task in the async runtime
let
result
=
rt.block_on
(
execute_async_task
(
)
)
;
// Handle the async task execution result
match
result
{
Ok
(
_
)
=>
println
!
(
"Async task executed successfully!"
)
,
Err
(
e
)
=>
eprintln
!
(
"Error: {}"
,
e
)
,
}
}
In the above code, we first imported the tokio and reqwest libraries, used for executing async tasks and making HTTP requests respectively. Then we defined an async function fetch_url for performing an async HTTP GET request and returning the response result.
Then we defined an async task execution function execute_async_task, which initiates the async HTTP request and outputs the response result.
Finally, in the main function we created a tokio async runtime, executed the async task in it, and handled the execution result of the async task.
Running this program, you can see the response result of the async HTTP request is output. The example requests a post data from JSONPlaceholder and prints its content.
Asynchronous Programming Notes
The async keyword
The async keyword is used to define async functions, i.e., functions that return a Future or impl Future type. When an async function executes, it returns an unfinished Future object, which represents a computation or operation that has not yet completed.
An async function can contain await expressions for waiting for the completion of other async operations.
Example
async
fn
hello
(
)
->
String
{
"Hello, world!"
.to_string
(
)
}
The await keyword
The await keyword is used to wait for the completion of an async operation and obtain its result.
An await expression can only be used in an async function or async block. It suspends the current async function execution, waits for the awaited Future to complete, and then continues executing the subsequent code.
Example
async
fn
print_hello
(
)
{
let
result
=
hello
(
)
.await
;
println
!
(
"{}"
,
result
)
;
}
Return Values of Async Functions
The return type of an async function is usually impl Future, where T which is the result type of the async operation. Since the return value of an async function is a Future, you can use .await to wait for the async operation to complete and obtain its result.
Example
async
fn
add
(
a
:
i32
,
b
:
i32
)
->
i32
{
a
b
}
Async Blocks
In addition to defining async functions, Rust also provides async block syntax, allowing the use of async operations in synchronous code. An async block is composed of async { } which can contain async function calls and await expression.
Example
async
{
let
result1
=
hello
(
)
.await
;
let
result2
=
add
(
1
,
2
)
.await
;
println
!
(
"Result: {}, {}"
,
result1
,
result2
)
;
}
;
Async Task Execution
In Rust, async tasks usually need to run in an execution context. You can use tokio::main、async-std 's task::block_on or futures::executor::block_on and other functions to execute async tasks. These functions accept an async function or async block and execute it in the current thread or execution environment.
Example
use
async_std
::
task
;
fn
main
(
)
{
task
::
block_on
(
print_hello
(
)
)
;
}
Error handling
await followed by a ? operator can propagate errors. If the await Future completes and returns an error, then that error will be propagated to the caller.
Example
async
fn
my_async_function
(
)
->
Result
<
(
)
,
MyError
{
some_async_operation
(
)
.await?;
// If some_async_operation fails, the error will be propagated
}
Async Trait Methods
Rust allows defining async methods for traits. This allows you to define async operations for objects of different types.
Example
trait
MyAsyncTrait
{
async
fn
async_method
(
&
self
)
->
Result
<
(
)
,
MyError;
}
impl
MyAsyncTrait
for
MyType
{
async
fn
async_method
(
&
self
)
->
Result
<
(
)
,
MyError
{// Async logic
}
}
Async Context
In Rust, async code is usually executed in an async runtime (such as Tokio or async-std). These runtimes provide mechanisms for scheduling and executing async tasks.
Example
[
tokio
::
main
]
async
fn
main
(
)
{
some_async_operation
(
)
.await
;
}
In the above code, the #[tokio::main] attribute macro wraps the main function in an async runtime.
Async Macros
Rust provides some async macros, such as tokio::spawn, for starting new async tasks in an async runtime.
Example
[
tokio
::
main
]
async
fn
main
(
)
{
let
handle
=
tokio
::
spawn
(
async
{
// Async logic
}
)
;
handle.await.unwrap
(
)
;
}
Async I/O
Rust's standard library provides async I/O operations, such as tokio::fs::File and async_std::fs::File.
Example
use
tokio
::
fs
::
File
;
use
tokio
::
io
::
{
self
,
AsyncReadExt
}
;
[
tokio
::
main
]
async
fn
main
(
)
->
io
::
Result
<
(
)
{
let
mut
file
=
File::
open
(
"file.txt"
)
.await?
;
let
mut
contents
=
String
::
new
(
)
;
file.read_to_string
(
&
mut
contents
)
.await?
;
println
!
(
"Contents: {}"
,
contents
)
;
Ok
(
(
)
)
}
Async Channels
Some of Rust's async runtimes provide async channels (such as tokio::sync::mpsc), allowing messages to be passed between async tasks.
Example
use
tokio
::
sync
::
mpsc
;
use
tokio
::
spawn
;
[
tokio
::
main
]
async
fn
main
(
)
{
let
(
tx
,
mut
rx
)
=
mpsc
::
channel
(
32
)
;
let
child
=
spawn
(
async move
{
let
response
=
"Hello, world!"
.to_string
(
)
;
tx.send
(
response
)
.await.unwrap
(
)
;
}
)
;
let
response
=
rx.recv
(
)
.await.unwrap
(
)
;
println
!
(
"Received: {}"
,
response
)
;
child.await.unwrap
(
)
;
}
Summary
Rust's async programming model async/await provides a concise and efficient way to handle async operations.
It allows developers to handle async operations in a more natural and intuitive way, while maintaining Rust's safety and performance.
Through async/await, Rust provides first-class language support for async programming, making it easier to write efficient and highly readable async programs.