What does this print?
fn main() {
let n = Box::new(42);
println!("{n}");
println!("{}", *n + 1);
}Running it prints:
42 43
Practice 13
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 13.
0 of 50 answered·0 correct
Box<T>: One Value on the HeapWhat does this print?
fn main() {
let n = Box::new(42);
println!("{n}");
println!("{}", *n + 1);
}Running it prints:
42 43
What does this print?
fn main() {
let word = Box::new(String::from("heap"));
println!("{}", word.len());
println!("{word}");
}Running it prints:
4 heap
What does this print? Box gives you the fields of the struct inside it directly, without writing * first.
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Box::new(Point { x: 3, y: 4 });
println!("{} {}", p.x, p.y);
}Running it prints:
3 4
What does this print?
fn add_one(b: Box<i32>) -> i32 {
*b + 1
}
fn main() {
let n = Box::new(9);
println!("{}", add_one(n));
}Running it prints:
10
What does this print?
fn main() {
let mut n = Box::new(5);
*n += 10;
println!("{n}");
}Running it prints:
15
A Box can hold another Box. What does this print?
fn main() {
let inner = Box::new(Box::new(7));
println!("{}", **inner);
}Running it prints:
7
Does this compile?
enum List {
Cons(i32, List),
Nil,
}
fn main() {
let list = List::Cons(1, List::Nil);
}The compiler says:
error[E0072]: recursive type `List` has infinite size
What does this print?
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
fn main() {
let list = Cons(10, Box::new(Cons(20, Box::new(Nil))));
let mut current = &list;
loop {
match current {
Cons(value, next) => {
println!("{value}");
current = next;
}
Nil => break,
}
}
}Running it prints:
10 20
What does this print?
fn main() {
let a = Box::new(3);
let b = Box::new(4);
println!("{}", *a + *b);
}Running it prints:
7
What does this print?
trait Shape {
fn area(&self) -> i32;
}
struct Square {
side: i32,
}
impl Shape for Square {
fn area(&self) -> i32 {
self.side * self.side
}
}
fn main() {
let shape: Box<dyn Shape> = Box::new(Square { side: 4 });
println!("{}", shape.area());
}Running it prints:
16
Rc<T>: More Than One OwnerWhat does this print?
use std::rc::Rc;
fn main() {
let name = Rc::new(String::from("Ada"));
println!("{}", Rc::strong_count(&name));
let second = Rc::clone(&name);
println!("{}", Rc::strong_count(&name));
}Running it prints:
1 2
What does this print?
use std::rc::Rc;
fn main() {
let n = Rc::new(1);
let mut owners = vec![];
for _ in 0..3 {
owners.push(Rc::clone(&n));
}
println!("{}", Rc::strong_count(&n));
}Running it prints:
4
What does this print?
use std::rc::Rc;
fn main() {
let n = Rc::new(100);
println!("{}", Rc::strong_count(&n));
{
let a = Rc::clone(&n);
let b = Rc::clone(&n);
println!("{}", Rc::strong_count(&n));
}
println!("{}", Rc::strong_count(&n));
}Running it prints:
1 3 1
What does this print?
use std::rc::Rc;
fn main() {
let numbers = Rc::new(vec![1, 2, 3]);
let copy = Rc::clone(&numbers);
let total: i32 = copy.iter().sum();
println!("{total}");
}Running it prints:
6
What does this print?
use std::rc::Rc;
fn main() {
let n = Rc::new(5);
let a = n.clone();
let b = Rc::clone(&n);
println!("{}", Rc::strong_count(&n));
}Running it prints:
3
What does this print?
use std::rc::Rc;
fn show(n: &Rc<i32>) {
println!("{}", Rc::strong_count(n));
}
fn main() {
let n = Rc::new(1);
let copy = Rc::clone(&n);
show(&n);
}Running it prints:
2
What does this print?
use std::rc::Rc;
fn keep(n: Rc<i32>) -> Rc<i32> {
println!("inside: {}", Rc::strong_count(&n));
n
}
fn main() {
let n = Rc::new(1);
let n = keep(Rc::clone(&n));
println!("outside: {}", Rc::strong_count(&n));
}Running it prints:
inside: 2 outside: 2
What does this print?
use std::rc::Rc;
struct Book {
title: String,
}
fn main() {
let book = Rc::new(Book { title: String::from("Rust in Practice") });
let shelf_copy = Rc::clone(&book);
let search_copy = Rc::clone(&book);
println!("{}", shelf_copy.title);
println!("{}", search_copy.title);
}Running it prints:
Rust in Practice Rust in Practice
Does this compile?
use std::rc::Rc;
fn main() {
let numbers = Rc::new(vec![1, 2, 3]);
let copy = Rc::clone(&numbers);
copy.push(4);
println!("{copy:?}");
}The compiler says:
error[E0596]: cannot borrow data in an `Rc` as mutable
What does this print?
use std::rc::Rc;
fn main() {
let n = Rc::new(String::from("shared"));
let a = Rc::clone(&n);
drop(a);
println!("{}", Rc::strong_count(&n));
drop(n);
}Running it prints:
1
RefCell<T>What does this print?
use std::cell::RefCell;
fn main() {
let n = RefCell::new(10);
*n.borrow_mut() += 5;
println!("{}", n.borrow());
}Running it prints:
15
What does this print?
use std::cell::RefCell;
fn main() {
let n = RefCell::new(1);
*n.borrow_mut() *= 2;
*n.borrow_mut() *= 2;
*n.borrow_mut() *= 2;
println!("{}", n.borrow());
}Running it prints:
8
Two reads never conflict, even through RefCell. What does this print?
use std::cell::RefCell;
fn main() {
let n = RefCell::new(7);
let a = n.borrow();
let b = n.borrow();
println!("{} {}", a, b);
}Running it prints:
7 7
What does this print?
use std::cell::RefCell;
fn main() {
let n = RefCell::new(0);
let a = n.borrow();
let b = n.borrow_mut();
println!("{a} {b}");
}Running it prints nothing.
Then it panics: RefCell already borrowed
What does this print?
use std::cell::RefCell;
fn main() {
let n = RefCell::new(0);
let a = n.borrow_mut();
let b = n.borrow_mut();
println!("{a} {b}");
}Running it prints nothing.
Then it panics: RefCell already borrowed
What does this print?
use std::cell::RefCell;
struct Counter {
hits: RefCell<i32>,
}
impl Counter {
fn hit(&self) {
*self.hits.borrow_mut() += 1;
}
}
fn main() {
let c = Counter { hits: RefCell::new(0) };
c.hit();
c.hit();
c.hit();
println!("{}", c.hits.borrow());
}Running it prints:
3
What does this print?
use std::cell::RefCell;
fn main() {
let list = RefCell::new(vec![1, 2]);
list.borrow_mut().push(3);
println!("{:?}", list.borrow());
}Running it prints:
[1, 2, 3]
drop(first) ends the borrow early, before the line that needed to write. What does this print?
use std::cell::RefCell;
fn main() {
let n = RefCell::new(1);
let first = n.borrow();
println!("{first}");
drop(first);
*n.borrow_mut() += 1;
println!("{}", n.borrow());
}Running it prints:
1 2
n is not declared mut. Does this compile, and what does it print?
use std::cell::RefCell;
fn main() {
let n = RefCell::new(5);
println!("{}", n.borrow_mut());
}Running it prints:
5
This line reads flag while its own borrow_mut() is still alive on the left of the same =. What does this print?
use std::cell::RefCell;
fn main() {
let flag = RefCell::new(false);
*flag.borrow_mut() = !*flag.borrow();
println!("{}", flag.borrow());
}Running it prints nothing.
Then it panics: RefCell already borrowed
Rc<RefCell<T>>: Shared and MutableWhat does this print?
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let count = Rc::new(RefCell::new(0));
let a = Rc::clone(&count);
let b = Rc::clone(&count);
*a.borrow_mut() += 10;
*b.borrow_mut() += 5;
println!("{}", count.borrow());
}Running it prints:
15
What does this print?
use std::cell::RefCell;
use std::rc::Rc;
struct Account {
balance: RefCell<i32>,
}
fn deposit(account: &Rc<Account>, amount: i32) {
*account.balance.borrow_mut() += amount;
}
fn main() {
let account = Rc::new(Account { balance: RefCell::new(100) });
let a = Rc::clone(&account);
let b = Rc::clone(&account);
let c = Rc::clone(&account);
deposit(&a, 10);
deposit(&b, 20);
deposit(&c, 30);
println!("{}", account.balance.borrow());
}Running it prints:
160
What does this print?
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let list = Rc::new(RefCell::new(vec![1]));
let a = Rc::clone(&list);
let b = Rc::clone(&list);
a.borrow_mut().push(2);
b.borrow_mut().push(3);
println!("{:?}", list.borrow());
}Running it prints:
[1, 2, 3]
What does this print?
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let n = Rc::new(RefCell::new(1));
println!("{}", Rc::strong_count(&n));
let a = Rc::clone(&n);
*a.borrow_mut() = 99;
println!("{}", Rc::strong_count(&n));
println!("{}", n.borrow());
}Running it prints:
1 2 99
first is still alive on the line that calls borrow_mut() through a. a and shared point at the same RefCell. What does this print?
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let shared = Rc::new(RefCell::new(0));
let a = Rc::clone(&shared);
let first = shared.borrow();
*a.borrow_mut() += 1;
println!("{first}");
}Running it prints nothing.
Then it panics: RefCell already borrowed
What does this print?
use std::cell::RefCell;
use std::rc::Rc;
struct Node {
value: i32,
next: Option<Rc<RefCell<Node>>>,
}
fn main() {
let second = Rc::new(RefCell::new(Node { value: 2, next: None }));
let first = Rc::new(RefCell::new(
Node { value: 1, next: Some(Rc::clone(&second)) }));
second.borrow_mut().value = 20;
let first_ref = first.borrow();
println!("{}", first_ref.value);
println!("{}", first_ref.next.as_ref().unwrap().borrow().value);
}Running it prints:
1 20
Does this compile?
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let numbers = Rc::new(RefCell::new(vec![1, 2, 3]));
let copy = Rc::clone(&numbers);
copy.push(4);
}The compiler says:
error[E0599]: no method named `push` found for struct `Rc<RefCell<Vec<{integer}>>>` in the current scopeWhat does this print?
use std::cell::RefCell;
use std::rc::Rc;
fn double(shared: Rc<RefCell<i32>>) {
let value = *shared.borrow();
*shared.borrow_mut() = value * 2;
}
fn main() {
let n = Rc::new(RefCell::new(6));
double(Rc::clone(&n));
double(Rc::clone(&n));
println!("{}", n.borrow());
}Running it prints:
24
Arc<T> and Mutex<T>What does this print?
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let counter2 = Arc::clone(&counter);
let handle = thread::spawn(move || {
*counter2.lock().unwrap() += 1;
});
handle.join().unwrap();
println!("{}", counter.lock().unwrap());
}Running it prints:
1
What does this print?
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let total = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..3 {
let total = Arc::clone(&total);
handles.push(thread::spawn(move || {
*total.lock().unwrap() += 5;
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("{}", total.lock().unwrap());
}Running it prints:
15
Arc keeps a count the same way Rc does. What does this print?
use std::sync::Arc;
fn main() {
let n = Arc::new(String::from("shared"));
let a = Arc::clone(&n);
let b = Arc::clone(&n);
println!("{}", Arc::strong_count(&n));
}Running it prints:
3
A spawned thread can hand back a value, through join(). What does this print?
use std::thread;
fn main() {
let handle = thread::spawn(|| {
3 + 4
});
let result = handle.join().unwrap();
println!("{result}");
}Running it prints:
7
What does this print?
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let names = Arc::new(Mutex::new(Vec::new()));
let a = Arc::clone(&names);
let handle_a = thread::spawn(move || {
a.lock().unwrap().push("first");
});
handle_a.join().unwrap();
let b = Arc::clone(&names);
let handle_b = thread::spawn(move || {
b.lock().unwrap().push("second");
});
handle_b.join().unwrap();
println!("{:?}", names.lock().unwrap());
}Running it prints:
["first", "second"]
What does this print?
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut guard = m.lock().unwrap();
*guard += 1;
}
println!("{}", m.lock().unwrap());
}Running it prints:
6
Does this compile?
use std::rc::Rc;
use std::cell::RefCell;
use std::thread;
fn main() {
let n = Rc::new(RefCell::new(0));
let handle = thread::spawn(move || {
*n.borrow_mut() += 1;
});
handle.join().unwrap();
}The compiler says:
error[E0277]: `Rc<RefCell<i32>>` cannot be sent between threads safely
(*numbers).clone() copies the vector itself, unlike Rc::clone, which only copies the pointer. What does this print?
use std::rc::Rc;
fn main() {
let numbers = Rc::new(vec![1, 2, 3]);
let mut copy = (*numbers).clone();
copy.push(4);
println!("{:?}", numbers);
println!("{:?}", copy);
}Running it prints:
[1, 2, 3] [1, 2, 3, 4]
Does this compile?
use std::thread;
fn main() {
let name = String::from("Ada");
let handle = thread::spawn(|| {
println!("{name}");
});
handle.join().unwrap();
}The compiler says:
error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function
What does this print?
trait Shape {
fn area(&self) -> i32;
}
struct Square { side: i32 }
struct Rectangle { width: i32, height: i32 }
impl Shape for Square {
fn area(&self) -> i32 { self.side * self.side }
}
impl Shape for Rectangle {
fn area(&self) -> i32 { self.width * self.height }
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Square { side: 3 }),
Box::new(Rectangle { width: 2, height: 5 }),
];
for shape in &shapes {
println!("{}", shape.area());
}
}Running it prints:
9 10
add_two keeps its own borrow_mut() alive in lines while it calls self.add(b), which tries to borrow the same RefCell again. What does this print?
use std::cell::RefCell;
struct Log {
lines: RefCell<Vec<String>>,
}
impl Log {
fn add(&self, line: &str) {
self.lines.borrow_mut().push(line.to_string());
}
fn add_two(&self, a: &str, b: &str) {
let mut lines = self.lines.borrow_mut();
lines.push(a.to_string());
self.add(b);
}
}
fn main() {
let log = Log { lines: RefCell::new(vec![]) };
log.add_two("first", "second");
}Running it prints nothing.
Then it panics: RefCell already borrowed
What does this print?
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let numbers = Rc::new(RefCell::new(vec![1, 2, 3, 4]));
let a = Rc::clone(&numbers);
a.borrow_mut().push(5);
let total: i32 = numbers.borrow().iter().sum();
println!("{total}");
println!("{}", Rc::strong_count(&numbers));
}Running it prints:
15 2