Practice 15

Async and Unsafe Rust

Read each program and pick an answer. Some programs do not compile, and that can be the right answer. Your choice is checked as soon as you pick it, and saved in this browser.Need a refresher? Read lesson 15.

Course

0 of 40 answered·0 correct

Running Async Code with tokio

1.

What does this print?

async fn double(n: i32) -> i32 {
    n * 2
}

#[tokio::main]
async fn main() {
    println!("{}", double(21).await);
}
2.

What does this print?

async fn greet(name: &str) -> String {
    format!("hello, {name}")
}

#[tokio::main]
async fn main() {
    println!("{}", greet("Ada").await);
}
3.

One async function awaits another inside its own body. What does this print?

async fn inner() -> i32 {
    10
}

async fn outer() -> i32 {
    inner().await + 5
}

#[tokio::main]
async fn main() {
    println!("{}", outer().await);
}
4.

Does this compile?

async fn main() {
    println!("hello");
}
5.

What does this print?

async fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[tokio::main]
async fn main() {
    let first = add(2, 3).await;
    let second = add(first, 10).await;
    println!("{second}");
}
6.

Does this compile?

fn main() {
    let result = add_one(4).await;
    println!("{result}");
}

async fn add_one(n: i32) -> i32 {
    n + 1
}

Futures Are Lazy

7.

What does this print?

async fn greet() {
    println!("hi");
}

#[tokio::main]
async fn main() {
    greet();
}
8.

What does this print?

async fn shout() {
    println!("loud");
}

#[tokio::main]
async fn main() {
    let future = shout();
    println!("before");
    future.await;
}
9.

What does this print?

async fn record(log: &mut Vec<i32>, value: i32) {
    log.push(value);
}

#[tokio::main]
async fn main() {
    let mut log = vec![];
    record(&mut log, 1).await;
    record(&mut log, 2).await;
    println!("{log:?}");
}
10.

handle.await returns a Result, the same as thread::spawn's join. Does this compile?

async fn compute() -> i32 {
    7
}

#[tokio::main]
async fn main() {
    let handle = tokio::spawn(compute());
    let result = handle.await;
    println!("{result}");
}

Running Futures at the Same Time

11.

What does this print?

use std::time::Duration;

async fn step(name: &str, ms: u64) {
    println!("{name} starting");
    tokio::time::sleep(Duration::from_millis(ms)).await;
    println!("{name} done");
}

#[tokio::main]
async fn main() {
    step("brew", 80).await;
    step("toast", 40).await;
}
12.

This is question 11 with tokio::join! in place of two separate .await calls. What does it print?

use std::time::Duration;

async fn step(name: &str, ms: u64) {
    println!("{name} starting");
    tokio::time::sleep(Duration::from_millis(ms)).await;
    println!("{name} done");
}

#[tokio::main]
async fn main() {
    tokio::join!(step("brew", 80), step("toast", 40));
}
13.

join! takes more than two futures at once. What does this print?

use std::time::Duration;

async fn step(name: &str, ms: u64) {
    println!("{name} starting");
    tokio::time::sleep(Duration::from_millis(ms)).await;
    println!("{name} done");
}

#[tokio::main]
async fn main() {
    tokio::join!(step("a", 30), step("b", 60), step("c", 10));
}
14.

What does this print?

async fn value(n: i32) -> i32 {
    n
}

#[tokio::main]
async fn main() {
    let handle = tokio::spawn(value(99));
    println!("{}", handle.await.unwrap());
}
15.

What does this print?

async fn square(n: i32) -> i32 {
    n * n
}

#[tokio::main]
async fn main() {
    let a = tokio::spawn(square(3));
    let b = tokio::spawn(square(4));
    let total = a.await.unwrap() + b.await.unwrap();
    println!("{total}");
}
16.

Does this compile?

async fn compute() -> i32 {
    7
}

#[tokio::main]
async fn main() {
    let handle = tokio::spawn(compute());
    println!("{}", handle.await);
}
17.

tokio::time::sleep is the async version of thread::sleep; using std::thread::sleep here blocks the whole thread, not just this one future, but the program still compiles and still runs one step after another. What does this print?

use std::time::Duration;

async fn step(name: &str, ms: u64) {
    println!("{name} starting");
    std::thread::sleep(Duration::from_millis(ms));
    println!("{name} done");
}

#[tokio::main]
async fn main() {
    step("one", 20).await;
    step("two", 10).await;
}
18.

What does this print?

async fn total(numbers: Vec<i32>) -> i32 {
    numbers.iter().sum()
}

#[tokio::main]
async fn main() {
    let a = tokio::spawn(total(vec![1, 2, 3]));
    let b = tokio::spawn(total(vec![4, 5]));
    println!("{}", a.await.unwrap() + b.await.unwrap());
}

Raw Pointers

19.

What does this print?

fn main() {
    let n = 9;
    let pointer: *const i32 = &n;

    unsafe {
        println!("{}", *pointer);
    }
}
20.

Does this compile?

fn main() {
    let n = 9;
    let pointer: *const i32 = &n;

    println!("{}", *pointer);
}
21.

let pointer: *const i32 = &n; needs no unsafe. Does this compile?

fn main() {
    let n = 9;
    let pointer: *const i32 = &n;
    println!("built the pointer");
}
22.

What does this print?

fn main() {
    let mut n = 2;
    let pointer: *mut i32 = &mut n;

    unsafe {
        *pointer *= 5;
    }

    println!("{n}");
}
23.

A raw pointer can be passed into a function like any other value. Only dereferencing it needs unsafe, not passing it. What does this print?

fn show(pointer: *const i32) {
    unsafe {
        println!("{}", *pointer);
    }
}

fn main() {
    let n = 9;
    let pointer: *const i32 = &n;
    show(pointer);
}
24.

Does this compile?

fn show(pointer: *const i32) {
    println!("{}", *pointer);
}

fn main() {
    let n = 9;
    show(&n);
}
25.

This compiles, with a warning. Why is pointer dangerous to dereference?

fn dangling() -> *const i32 {
    let x = 7;
    &x as *const i32
}

fn main() {
    let pointer = dangling();
    unsafe {
        println!("{}", *pointer);
    }
}
26.

Does this compile?

fn safe_version() -> i32 {
    let x = 7;
    x
}

fn main() {
    let value = safe_version();
    println!("{value}");
}

The unsafe Block

27.

What does this print?

unsafe fn triple(n: *mut i32) {
    unsafe {
        *n *= 3;
    }
}

fn main() {
    let mut value = 4;
    let pointer: *mut i32 = &mut value;

    unsafe {
        triple(pointer);
    }

    println!("{value}");
}
28.

Does this compile?

unsafe fn triple(n: *mut i32) {
    unsafe {
        *n *= 3;
    }
}

fn main() {
    let mut value = 4;
    let pointer: *mut i32 = &mut value;

    triple(pointer);

    println!("{value}");
}
29.

This unsafe fn does not wrap its own body in an unsafe block. It still compiles, with a warning, because the unsafe on the function changes only what callers must do. What does this print?

unsafe fn triple(n: *mut i32) {
    *n *= 3;
}

fn main() {
    let mut value = 4;
    let pointer: *mut i32 = &mut value;

    unsafe {
        triple(pointer);
    }

    println!("{value}");
}
30.

What does this print?

unsafe fn read_and_clear(n: *mut i32) -> i32 {
    unsafe {
        let value = *n;
        *n = 0;
        value
    }
}

fn main() {
    let mut n = 12;
    let pointer: *mut i32 = &mut n;

    let old = unsafe { read_and_clear(pointer) };

    println!("{old} {n}");
}
31.

Does this compile?

fn main() {
    let mut n = 5;
    let a: *mut i32 = &mut n;
    let b: *mut i32 = &mut n;

    unsafe {
        *a += 1;
        *b += 1;
    }

    println!("{n}");
}
32.

Two ordinary &mut references to the same variable, alive at the same time, are refused by the borrow checker even though question 31's raw pointers were not. Does this compile?

fn main() {
    let mut n = 5;
    let a = &mut n;
    let b = &mut n;

    *a += 1;
    *b += 1;

    println!("{n}");
}
33.

What does this print?

struct Counter {
    value: i32,
}

unsafe fn bump(c: *mut Counter) {
    unsafe {
        (*c).value += 1;
    }
}

fn main() {
    let mut c = Counter { value: 0 };
    let pointer: *mut Counter = &mut c;

    unsafe {
        bump(pointer);
        bump(pointer);
    }

    println!("{}", c.value);
}
34.

Does this compile?

fn main() {
    let n = 5;
    let pointer: *const i32 = &n;
    let doubled = *pointer * 2;
    println!("{doubled}");
}

Mixed Review

35.

What does this print?

async fn read(pointer: *const i32) -> i32 {
    unsafe { *pointer }
}

#[tokio::main]
async fn main() {
    let n = 40;
    let pointer: *const i32 = &n;
    println!("{}", read(pointer).await);
}
36.

Does this compile?

async fn read(pointer: *const i32) -> i32 {
    *pointer
}

#[tokio::main]
async fn main() {
    let n = 40;
    let pointer: *const i32 = &n;
    println!("{}", read(pointer).await);
}
37.

What does this print?

use std::time::Duration;

async fn deposit(total: &mut i32, amount: i32, ms: u64) {
    tokio::time::sleep(Duration::from_millis(ms)).await;
    *total += amount;
}

#[tokio::main]
async fn main() {
    let mut total = 0;
    deposit(&mut total, 10, 20).await;
    deposit(&mut total, 5, 10).await;
    println!("{total}");
}
38.

What does this print?

unsafe fn negate(n: *mut i32) {
    unsafe {
        *n = -*n;
    }
}

async fn run(n: *mut i32) {
    unsafe {
        negate(n);
    }
}

#[tokio::main]
async fn main() {
    let mut value = 8;
    let pointer: *mut i32 = &mut value;
    run(pointer).await;
    println!("{value}");
}
39.

Does this compile?

fn dangling() -> *const i32 {
    let n = 3;
    &n as *const i32
}

async fn read() -> i32 {
    let pointer = dangling();
    unsafe { *pointer }
}

#[tokio::main]
async fn main() {
    read();
}
40.

What does this print?

async fn score(id: i32) -> i32 {
    id * id
}

#[tokio::main]
async fn main() {
    let mut handles = vec![];
    for id in 1..=3 {
        handles.push(tokio::spawn(score(id)));
    }

    let mut total = 0;
    for handle in handles {
        total += handle.await.unwrap();
    }
    println!("{total}");
}