mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-09-29 10:13:29 +00:00
feat: add async exercises
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_worker() -> i32 {
|
||||
// TODO: Make our worker create a new number and return it.
|
||||
Worker.work().await.extract_number().await
|
||||
}
|
||||
|
||||
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]
|
||||
// TODO: Fix the test function signature
|
||||
fn test_if_it_works() {
|
||||
let number = run_worker().await;
|
||||
assert_eq!(number, 32);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
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(async move { i });
|
||||
}
|
||||
|
||||
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?
|
||||
tasks.join_all().await
|
||||
}
|
||||
|
||||
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]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user