What does this print?
async fn double(n: i32) -> i32 {
n * 2
}
#[tokio::main]
async fn main() {
println!("{}", double(21).await);
}Running it prints:
42
Practice 15
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.
0 of 40 answered·0 correct
tokioWhat does this print?
async fn double(n: i32) -> i32 {
n * 2
}
#[tokio::main]
async fn main() {
println!("{}", double(21).await);
}Running it prints:
42
What does this print?
async fn greet(name: &str) -> String {
format!("hello, {name}")
}
#[tokio::main]
async fn main() {
println!("{}", greet("Ada").await);
}Running it prints:
hello, Ada
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);
}Running it prints:
15
Does this compile?
async fn main() {
println!("hello");
}The compiler says:
error[E0752]: `main` function is not allowed to be `async`
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}");
}Running it prints:
15
Does this compile?
fn main() {
let result = add_one(4).await;
println!("{result}");
}
async fn add_one(n: i32) -> i32 {
n + 1
}The compiler says:
error[E0728]: `await` is only allowed inside `async` functions and blocks
What does this print?
async fn greet() {
println!("hi");
}
#[tokio::main]
async fn main() {
greet();
}Running it prints nothing.
What does this print?
async fn shout() {
println!("loud");
}
#[tokio::main]
async fn main() {
let future = shout();
println!("before");
future.await;
}Running it prints:
before loud
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:?}");
}Running it prints:
[1, 2]
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}");
}The compiler says:
error[E0277]: `Result<i32, JoinError>` doesn't implement `std::fmt::Display`
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;
}Running it prints:
brew starting brew done toast starting toast done
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));
}Running it prints:
brew starting toast starting toast done brew done
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));
}Running it prints:
a starting b starting c starting c done a done b done
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());
}Running it prints:
99
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}");
}Running it prints:
25
Does this compile?
async fn compute() -> i32 {
7
}
#[tokio::main]
async fn main() {
let handle = tokio::spawn(compute());
println!("{}", handle.await);
}The compiler says:
error[E0277]: `Result<i32, JoinError>` doesn't implement `std::fmt::Display`
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;
}Running it prints:
one starting one done two starting two done
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());
}Running it prints:
15
What does this print?
fn main() {
let n = 9;
let pointer: *const i32 = &n;
unsafe {
println!("{}", *pointer);
}
}Running it prints:
9
Does this compile?
fn main() {
let n = 9;
let pointer: *const i32 = &n;
println!("{}", *pointer);
}The compiler says:
error[E0133]: dereference of raw pointer is unsafe and requires unsafe function or block
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");
}Running it prints:
built the pointer
What does this print?
fn main() {
let mut n = 2;
let pointer: *mut i32 = &mut n;
unsafe {
*pointer *= 5;
}
println!("{n}");
}Running it prints:
10
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);
}Running it prints:
9
Does this compile?
fn show(pointer: *const i32) {
println!("{}", *pointer);
}
fn main() {
let n = 9;
show(&n);
}The compiler says:
error[E0133]: dereference of raw pointer is unsafe and requires unsafe function or block
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);
}
}One run here printed 1, not 7: whatever happened to be left in that memory.
Does this compile?
fn safe_version() -> i32 {
let x = 7;
x
}
fn main() {
let value = safe_version();
println!("{value}");
}Running it prints:
7
unsafe BlockWhat 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}");
}Running it prints:
12
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}");
}The compiler says:
error[E0133]: call to unsafe function `triple` is unsafe and requires unsafe function or block
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}");
}Running it prints:
12
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}");
}Running it prints:
12 0
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}");
}Running it prints:
7
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}");
}The compiler says:
error[E0499]: cannot borrow `n` as mutable more than once at a time
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);
}Running it prints:
2
Does this compile?
fn main() {
let n = 5;
let pointer: *const i32 = &n;
let doubled = *pointer * 2;
println!("{doubled}");
}The compiler says:
error[E0133]: dereference of raw pointer is unsafe and requires unsafe function or block
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);
}Running it prints:
40
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);
}The compiler says:
error[E0133]: dereference of raw pointer is unsafe and requires unsafe block
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}");
}Running it prints:
15
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}");
}Running it prints:
-8
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();
}Running it prints nothing.
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}");
}Running it prints:
14