Practice 09

Structuring Data

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

Course

0 of 50 answered·0 correct

Structs and Fields

1.

What does this print?

struct Coin {
    label: String,
    value: u32,
}

fn main() {
    let c = Coin { label: String::from("rupee"), value: 1 };
    println!("{}", c.label);
    println!("{}", c.value);
}
2.

What does this print?

struct Counter {
    total: u32,
}

fn main() {
    let mut c = Counter { total: 0 };
    c.total = c.total + 5;
    c.total = c.total + 2;
    println!("{}", c.total);
}
3.

c is not declared with mut here. Does this compile?

struct Counter {
    total: u32,
}

fn main() {
    let c = Counter { total: 0 };
    c.total = 5;
    println!("{}", c.total);
}
4.

What does this print?

struct Player {
    name: String,
    score: u32,
}

fn main() {
    let name = String::from("Kiran");
    let score = 40;

    let p = Player { name, score };
    println!("{} {}", p.name, p.score);
}
5.

What does this print?

struct Player {
    name: String,
    score: u32,
}

fn main() {
    let first = Player { name: String::from("Kiran"), score: 40 };
    let second = Player { score: 55, ..first };

    println!("{} {}", second.name, second.score);
}
6.

What does this print?

#[derive(Debug)]
struct Box2 {
    width: u32,
    height: u32,
}

fn main() {
    let b = Box2 { width: 3, height: 4 };
    println!("{b:?}");
    println!("{b:#?}");
}
7.

Does this compile?

struct Box2 {
    width: u32,
    height: u32,
}

fn main() {
    let b = Box2 { width: 3, height: 4 };
    println!("{}", b);
}
8.

What does this print?

struct Pair(i32, i32);

fn main() {
    let p = Pair(10, -3);
    println!("{} {}", p.0, p.1);
}
9.

Does this compile?

struct Player {
    name: String,
    score: u32,
}

fn main() {
    let first = Player { name: String::from("Kiran"), score: 40 };
    let second = Player { score: 55, ..first };

    println!("{} {}", first.name, second.score);
}
10.

The fields are written in a different order from the struct definition. What does this print?

struct Player {
    name: String,
    score: u32,
}

fn main() {
    let p = Player { score: 12, name: String::from("Wei") };
    println!("{} {}", p.name, p.score);
}

Methods and impl Blocks

11.

What does this print?

struct Rect {
    width: u32,
    height: u32,
}

impl Rect {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let r = Rect { width: 6, height: 3 };
    println!("{}", r.area());
}
12.

What does this print?

struct Counter {
    total: u32,
}

impl Counter {
    fn add(&mut self, amount: u32) {
        self.total += amount;
    }
}

fn main() {
    let mut c = Counter { total: 0 };
    c.add(3);
    c.add(4);
    println!("{}", c.total);
}
13.

Does this compile?

struct Ticket {
    code: String,
}

impl Ticket {
    fn use_it(self) -> String {
        self.code
    }
}

fn main() {
    let t = Ticket { code: String::from("A102") };
    let code = t.use_it();
    println!("{code}");
    println!("{}", t.code);
}
14.

What does this print?

struct Rect {
    width: u32,
    height: u32,
}

impl Rect {
    fn square(side: u32) -> Rect {
        Rect { width: side, height: side }
    }

    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let r = Rect::square(5);
    println!("{}", r.area());
}
15.

Does this compile?

struct Rect {
    width: u32,
    height: u32,
}

impl Rect {
    fn square(side: u32) -> Rect {
        Rect { width: side, height: side }
    }
}

fn main() {
    let r = Rect.square(5);
    println!("{}", r.width);
}
16.

What does this print?

struct Counter {
    total: u32,
}

impl Counter {
    fn new() -> Counter {
        Counter { total: 0 }
    }

    fn add(&mut self, amount: u32) -> u32 {
        self.total += amount;
        self.total
    }
}

fn main() {
    let mut c = Counter::new();
    println!("{}", c.add(10));
    println!("{}", c.add(5));
}
17.

What does this print?

struct Account {
    balance: i32,
}

impl Account {
    fn new(balance: i32) -> Account {
        Account { balance }
    }

    fn deposit(&mut self, amount: i32) {
        self.balance += amount;
    }

    fn withdraw(&mut self, amount: i32) {
        self.balance -= amount;
    }

    fn is_overdrawn(&self) -> bool {
        self.balance < 0
    }
}

fn main() {
    let mut a = Account::new(50);
    a.deposit(20);
    a.withdraw(100);
    println!("{}", a.balance);
    println!("{}", a.is_overdrawn());
}
18.

One method calls another method on the same value with self.area(). What does this print?

struct Rect {
    width: u32,
    height: u32,
}

impl Rect {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn describe(&self) -> String {
        if self.area() > 20 {
            String::from("big")
        } else {
            String::from("small")
        }
    }
}

fn main() {
    let r = Rect { width: 5, height: 5 };
    println!("{}", r.describe());
}
19.

grow takes &self, not self, so it builds a new Rect instead of changing the old one. What does this print?

struct Rect {
    width: u32,
    height: u32,
}

impl Rect {
    fn new(width: u32, height: u32) -> Rect {
        Rect { width, height }
    }

    fn grow(&self, amount: u32) -> Rect {
        Rect { width: self.width + amount, height: self.height + amount }
    }

    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let r = Rect::new(2, 3);
    let bigger = r.grow(1);
    println!("{}", r.area());
    println!("{}", bigger.area());
}
20.

What does this print?

struct Student {
    name: String,
    marks: u32,
}

impl Student {
    fn passed(&self) -> bool {
        self.marks >= 40
    }
}

fn main() {
    let students = vec![
        Student { name: String::from("Asha"), marks: 71 },
        Student { name: String::from("Bo"), marks: 30 },
        Student { name: String::from("Cy"), marks: 40 },
    ];

    for s in &students {
        println!("{} {}", s.name, s.passed());
    }
}

Enums and match

21.

What does this print?

enum Light {
    Red,
    Yellow,
    Green,
}

fn main() {
    let signal = Light::Green;

    match signal {
        Light::Red => println!("stop"),
        Light::Yellow => println!("wait"),
        Light::Green => println!("go"),
    }
}
22.

What does this print?

enum Shape {
    Circle(f64),
    Square(f64),
}

fn area(shape: &Shape) -> f64 {
    match shape {
        Shape::Circle(radius) => 3.0 * radius * radius,
        Shape::Square(side) => side * side,
    }
}

fn main() {
    let s = Shape::Square(4.0);
    println!("{}", area(&s));
}
23.

Does this compile?

enum Light {
    Red,
    Yellow,
    Green,
}

fn word(signal: Light) -> &'static str {
    match signal {
        Light::Red => "stop",
        Light::Green => "go",
    }
}

fn main() {
    println!("{}", word(Light::Red));
}
24.

match produces a value here, and that value is stored in price. What does this print?

enum Size {
    Small,
    Medium,
    Large,
}

fn main() {
    let s = Size::Medium;

    let price = match s {
        Size::Small => 30,
        Size::Medium => 50,
        Size::Large => 70,
    };

    println!("{price}");
}
25.

What does this print?

enum Shape {
    Circle(f64),
    Square(f64),
    Point,
}

fn area(shape: &Shape) -> f64 {
    match shape {
        Shape::Circle(radius) => 3.0 * radius * radius,
        Shape::Square(side) => side * side,
        Shape::Point => 0.0,
    }
}

fn main() {
    let shapes = [Shape::Circle(2.0), Shape::Point, Shape::Square(3.0)];

    for shape in &shapes {
        println!("{}", area(shape));
    }
}
26.

status is a field of p, and that field is an enum. What does this print?

enum Status {
    Active,
    Retired(u32),
}

struct Player {
    name: String,
    status: Status,
}

fn main() {
    let p = Player {
        name: String::from("Wei"),
        status: Status::Retired(2019),
    };

    let name = &p.name;
    match p.status {
        Status::Active => println!("{name} is active"),
        Status::Retired(year) => println!("{name} retired in {year}"),
    }
}
27.

What does this print?

#[derive(Debug)]
enum Status {
    Active,
    Retired(u32),
}

fn main() {
    let s = Status::Retired(2019);
    println!("{s:?}");
}
28.

Does this compile?

enum Status {
    Active,
    Retired(u32),
}

fn main() {
    let s = Status::Active;
    println!("{s:?}");
}
29.

This compiles. What does it print?

enum Shape {
    Circle(f64),
    Square(f64),
}

fn label(shape: &Shape) -> &'static str {
    match shape {
        Shape::Circle(radius) if *radius > 5.0 => "big circle",
        Shape::Circle(_) => "small circle",
        Shape::Square(_) => "square",
    }
}

fn main() {
    let s = Shape::Circle(8.0);
    println!("{}", label(&s));
}
30.

The method itself contains the match. What does this print?

enum Shape {
    Circle(f64),
    Square(f64),
}

impl Shape {
    fn area(&self) -> f64 {
        match self {
            Shape::Circle(radius) => 3.0 * radius * radius,
            Shape::Square(side) => side * side,
        }
    }
}

fn main() {
    let shapes = [Shape::Circle(1.0), Shape::Square(2.0)];
    let mut total = 0.0;

    for shape in &shapes {
        total += shape.area();
    }

    println!("{total}");
}
31.

Does this compile?

enum Coin {
    Penny,
    Nickel,
    Dime,
}

fn value(coin: Coin) -> u32 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
    }
}

fn main() {
    println!("{}", value(Coin::Dime));
}
32.

grade is a method that returns an enum. What does this print?

enum Grade {
    Pass,
    Fail,
}

struct Student {
    name: String,
    marks: u32,
}

impl Student {
    fn grade(&self) -> Grade {
        if self.marks >= 40 {
            Grade::Pass
        } else {
            Grade::Fail
        }
    }
}

fn report(s: &Student) {
    let word = match s.grade() {
        Grade::Pass => "pass",
        Grade::Fail => "fail",
    };
    println!("{} {word}", s.name);
}

fn main() {
    let students = [
        Student { name: String::from("Asha"), marks: 71 },
        Student { name: String::from("Bo"), marks: 30 },
    ];

    for s in &students {
        report(s);
    }
}

Option, if let and while let

33.

What does this print?

fn find_even(n: i32) -> Option<i32> {
    if n % 2 == 0 {
        Some(n)
    } else {
        None
    }
}

fn main() {
    match find_even(7) {
        Some(n) => println!("even: {n}"),
        None => println!("odd"),
    }
}
34.

What does this print?

fn main() {
    let marks = vec![71, 64, 88];

    println!("{}", marks.get(2).copied().unwrap_or(0));
    println!("{}", marks.get(5).copied().unwrap_or(0));
}
35.

What does this print?

fn main() {
    let town: Option<String> = None;

    if let Some(name) = town {
        println!("town is {name}");
    } else {
        println!("no town");
    }
}
36.

There is no else here. What does this print?

fn main() {
    let count: Option<u32> = Some(3);

    if let Some(n) = count {
        println!("count is {n}");
    }

    println!("done");
}
37.

What does this print?

fn main() {
    let mut queue = vec!["a", "b", "c"];

    while let Some(item) = queue.pop() {
        println!("{item}");
    }

    println!("empty");
}
38.

What does this print?

fn main() {
    let name: Option<String> = Some(String::from("Lima"));
    println!("{}", name.unwrap_or(String::from("unknown")));
}
39.

Does this compile?

fn main() {
    let count: Option<i32> = Some(4);
    let total = count + 1;
    println!("{total}");
}
40.

What does this print?

fn half_if_even(n: i32) -> Option<i32> {
    if n % 2 == 0 {
        Some(n / 2)
    } else {
        None
    }
}

fn main() {
    for n in [4, 7, 10] {
        if let Some(half) = half_if_even(n) {
            println!("{n} halves to {half}");
        } else {
            println!("{n} is odd");
        }
    }
}

Result, panic! and the ? Operator

41.

What does this print?

fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        Err(String::from("cannot divide by zero"))
    } else {
        Ok(a / b)
    }
}

fn main() {
    match divide(9.0, 3.0) {
        Ok(value) => println!("answer: {value}"),
        Err(message) => println!("failed: {message}"),
    }
}
42.

What does this print?

fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        Err(String::from("cannot divide by zero"))
    } else {
        Ok(a / b)
    }
}

fn main() {
    for pair in [(8.0, 2.0), (5.0, 0.0)] {
        match divide(pair.0, pair.1) {
            Ok(value) => println!("answer: {value}"),
            Err(message) => println!("failed: {message}"),
        }
    }
}
43.

What does the first call print? The second call panics before it prints anything.

fn withdraw(balance: u32, amount: u32) -> u32 {
    if amount > balance {
        panic!("asked for {amount} but the balance is only {balance}");
    }
    balance - amount
}

fn main() {
    println!("left: {}", withdraw(200, 50));
    println!("left: {}", withdraw(200, 900));
}
44.

What does the first line print? What does unwrap do on the second parse?

fn main() {
    let text = "13";
    let number: i32 = text.parse().unwrap();
    println!("{number}");

    let bad = "thirteen";
    let broken: i32 = bad.parse().unwrap();
    println!("never printed: {broken}");
}
45.

"nine" is text, not a number, so parse returns an Err. What does expect do with it?

fn main() {
    let text = "nine";
    let number: i32 = text.parse().expect("not a whole number");
    println!("{number}");
}
46.

What does this print?

fn main() {
    let text = "56";
    let number: i32 = text.parse().unwrap();
    println!("{}", number + 4);
}
47.

What does this print?

use std::num::ParseIntError;

fn add_text(a: &str, b: &str) -> Result<i32, ParseIntError> {
    let first: i32 = a.parse()?;
    let second: i32 = b.parse()?;
    Ok(first + second)
}

fn main() {
    match add_text("15", "9") {
        Ok(total) => println!("total: {total}"),
        Err(error) => println!("failed: {error}"),
    }

    match add_text("15", "nine") {
        Ok(total) => println!("total: {total}"),
        Err(error) => println!("failed: {error}"),
    }
}
48.

? also works on Option, in a function that returns an Option. What does this print?

fn first_letter(text: &str) -> Option<char> {
    let c = text.chars().next()?;
    Some(c.to_ascii_uppercase())
}

fn main() {
    println!("{:?}", first_letter("delhi"));
    println!("{:?}", first_letter(""));
}
49.

A struct, an enum, and an associated function that returns an Option. What does this print?

struct Reading {
    town: String,
    degrees: i32,
}

enum Level {
    Cold,
    Hot,
}

impl Reading {
    fn parse(line: &str) -> Option<Reading> {
        let mut parts = line.split(' ');
        let town = parts.next()?;
        let degrees = parts.next()?.parse().ok()?;
        Some(Reading { town: String::from(town), degrees })
    }

    fn level(&self) -> Level {
        if self.degrees < 20 {
            Level::Cold
        } else {
            Level::Hot
        }
    }
}

fn report(line: &str) {
    match Reading::parse(line) {
        Some(reading) => {
            let word = match reading.level() {
                Level::Cold => "cold",
                Level::Hot => "hot",
            };
            println!("{} is {word}", reading.town);
        }
        None => println!("bad line: {line}"),
    }
}

fn main() {
    report("Tokyo 12");
    report("Cairo 38");
    report("Perth mild");
}
50.

The last two arms both match Job::Done, and the guard on the first one decides which arm is used. What does this print?

enum Job {
    Queued,
    Running(u32),
    Done(u32),
}

impl Job {
    fn status(&self) -> String {
        match self {
            Job::Queued => String::from("queued"),
            Job::Running(pct) => format!("running at {pct}%"),
            Job::Done(code) if *code == 0 => String::from("done, ok"),
            Job::Done(code) => format!("done, error {code}"),
        }
    }
}

fn main() {
    let jobs = [Job::Queued, Job::Running(40), Job::Done(0), Job::Done(2)];

    for j in &jobs {
        println!("{}", j.status());
    }
}