Practice 13

Smart Pointers

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.

Course

0 of 50 answered·0 correct

Box<T>: One Value on the Heap

1.

What does this print?

fn main() {
    let n = Box::new(42);
    println!("{n}");
    println!("{}", *n + 1);
}
2.

What does this print?

fn main() {
    let word = Box::new(String::from("heap"));
    println!("{}", word.len());
    println!("{word}");
}
3.

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);
}
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));
}
5.

What does this print?

fn main() {
    let mut n = Box::new(5);
    *n += 10;
    println!("{n}");
}
6.

A Box can hold another Box. What does this print?

fn main() {
    let inner = Box::new(Box::new(7));
    println!("{}", **inner);
}
7.

Does this compile?

enum List {
    Cons(i32, List),
    Nil,
}

fn main() {
    let list = List::Cons(1, List::Nil);
}
8.

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,
        }
    }
}
9.

What does this print?

fn main() {
    let a = Box::new(3);
    let b = Box::new(4);
    println!("{}", *a + *b);
}
10.

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());
}

Rc<T>: More Than One Owner

11.

What 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));
}
12.

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));
}
13.

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));
}
14.

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}");
}
15.

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));
}
16.

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);
}
17.

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));
}
18.

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);
}
19.

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:?}");
}
20.

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);
}

Interior Mutability and RefCell<T>

21.

What does this print?

use std::cell::RefCell;

fn main() {
    let n = RefCell::new(10);
    *n.borrow_mut() += 5;
    println!("{}", n.borrow());
}
22.

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());
}
23.

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);
}
24.

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}");
}
25.

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}");
}
26.

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());
}
27.

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());
}
28.

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());
}
29.

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());
}
30.

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());
}

Rc<RefCell<T>>: Shared and Mutable

31.

What 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());
}
32.

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());
}
33.

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());
}
34.

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());
}
35.

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}");
}
36.

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);
}
37.

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);
}
38.

What 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());
}

Arc<T> and Mutex<T>

39.

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());
}
40.

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());
}
41.

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));
}
42.

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}");
}
43.

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());
}
44.

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());
}
45.

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();
}

Mixed Review

46.

(*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);
}
47.

Does this compile?

use std::thread;

fn main() {
    let name = String::from("Ada");
    let handle = thread::spawn(|| {
        println!("{name}");
    });
    handle.join().unwrap();
}
48.

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());
    }
}
49.

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");
}
50.

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));
}