feat: add async exercises

This commit is contained in:
liv
2025-05-16 15:53:31 +02:00
parent e73fff3bd4
commit b2b3005670
35 changed files with 268 additions and 36 deletions
+10
View File
@@ -0,0 +1,10 @@
# Async
Rust includes built-in support for asynchronous programming. In other languages, this might be known as Promises or
Coroutines. async programming uses async functions, which are powerful, but may require some getting used to,
especially if you haven't used something similar in another language.
The [relevant book chapter][1] is essential reading. The [tokio docs][2] are also very helpful!
[1]: https://doc.rust-lang.org/book/ch17-00-async-await.html
[2]: https://tokio.rs/tokio/tutorial
+44
View File
@@ -0,0 +1,44 @@
// Our loyal worker works hard to create a new number.
#[derive(Default)]
struct Worker;
struct NumberContainer {
number: i32,
}
impl Worker {
async fn work(&self) -> NumberContainer {
// Pretend this takes a while...
let new_number = 32;
NumberContainer { number: new_number }
}
}
impl NumberContainer {
async fn extract_number(&self) -> i32 {
// And this too...
self.number
}
}
// TODO: Fix the function signature!
fn run_worker() -> i32 {
// TODO: Make our worker create a new number and return it.
}
fn main() {
// Feel free to experiment here. You may need to make some adjustments
// to this function, though.
}
mod tests {
use super::*;
// Don't worry about this attribute for now.
// If you want to know what this does, read the hint!
#[tokio::test]
async fn test_if_it_works() {
let number = run_worker().await;
assert_eq!(number, 32);
}
}
+42
View File
@@ -0,0 +1,42 @@
use tokio::task::JoinSet;
// A MultiWorker can work with the power of 5 normal workers,
// allowing us to create 5 new numbers at once!
struct MultiWorker;
impl MultiWorker {
async fn start_work(&self) -> JoinSet<i32> {
let mut set = JoinSet::new();
for i in 30..35 {
// TODO: `set.spawn` accepts an async function that will return the number
// we want. Implement this function as a closure!
set.spawn(???);
}
set
}
}
async fn run_multi_worker() -> Vec<i32> {
let tasks = MultiWorker.start_work().await;
// TODO: We have a bunch of tasks, how do we run them to completion
// to get at the i32s they create?
}
fn main() {
// Feel free to experiment here. You may need to make some adjustments
// to this function, though.
}
mod tests {
use super::*;
#[tokio::test]
async fn test_if_it_works() {
let mut numbers = run_multi_worker().await;
numbers.sort(); // in case tasks run out-of-order
assert_eq!(numbers, vec![30, 31, 32, 33, 34]);
}
}