Practice 16

Macros and Advanced Traits

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

Course

0 of 42 answered·0 correct

Declarative Macros with macro_rules!

1.

What does this print?

macro_rules! cube {
    ($x:expr) => {
        $x * $x * $x
    };
}

fn main() {
    println!("{}", cube!(3));
}
2.

What does this print?

macro_rules! announce {
    ($x:expr, $y:expr) => {
        format!("{} and {}", $x, $y)
    };
}

fn main() {
    println!("{}", announce!("cats", "dogs"));
}
3.

A macro can call itself, or another macro, inside its own replacement. What does this print?

macro_rules! double {
    ($x:expr) => {
        $x * 2
    };
}

macro_rules! quadruple {
    ($x:expr) => {
        double!(double!($x))
    };
}

fn main() {
    println!("{}", quadruple!(3));
}
4.

greet! only matches an empty argument list. Does this compile?

macro_rules! greet {
    () => {
        println!("hi");
    };
}

fn main() {
    greet!(5);
}
5.

A macro has to be defined before the line that calls it, reading top to bottom, the same as a variable. Does this compile?

fn main() {
    println!("{}", triple!(4));
}

macro_rules! triple {
    ($x:expr) => {
        $x * 3
    };
}
6.

What does this print?

macro_rules! greet {
    () => {
        println!("hello from a macro");
    };
}

fn main() {
    greet!();
    greet!();
}

Matching More Than One Pattern

7.

What does this print?

macro_rules! biggest {
    ($x:expr) => {
        $x
    };
    ($x:expr, $y:expr) => {
        if $x > $y { $x } else { $y }
    };
}

fn main() {
    println!("{}", biggest!(7));
    println!("{}", biggest!(2, 8));
}
8.

Rules are tried from the top. What does this print?

macro_rules! describe {
    () => {
        String::from("nothing")
    };
    ($x:expr) => {
        format!("one: {}", $x)
    };
    ($x:expr, $y:expr) => {
        format!("two: {} and {}", $x, $y)
    };
}

fn main() {
    println!("{}", describe!());
    println!("{}", describe!(5));
    println!("{}", describe!(5, 6));
}
9.

Does this compile?

macro_rules! describe {
    ($x:expr) => {
        format!("one: {}", $x)
    };
    ($x:expr, $y:expr) => {
        format!("two: {} and {}", $x, $y)
    };
}

fn main() {
    println!("{}", describe!(1, 2, 3));
}
10.

What does this print?

macro_rules! shout {
    ($x:expr) => {
        format!("{}!", $x)
    };
    ($x:expr, $n:expr) => {
        format!("{}{}", $x, "!".repeat($n))
    };
}

fn main() {
    println!("{}", shout!("hi"));
    println!("{}", shout!("hi", 3));
}

Repetition in a Macro

11.

What does this print?

macro_rules! sum {
    ($($x:expr),*) => {{
        let mut total = 0;
        $(total += $x;)*
        total
    }};
}

fn main() {
    println!("{}", sum!(1, 2, 3, 4));
}
12.

What does this print?

macro_rules! product {
    ($($x:expr),*) => {{
        let mut total = 1;
        $(total *= $x;)*
        total
    }};
}

fn main() {
    println!("{}", product!(2, 3, 4));
}
13.

$(...),* matches zero expressions just as well as several. What does this print?

macro_rules! sum {
    ($($x:expr),*) => {{
        let mut total = 0;
        $(total += $x;)*
        total
    }};
}

fn main() {
    println!("{}", sum!());
}
14.

Each matched expression adds one hidden 1, so the whole sum counts how many were passed in. What does this print?

macro_rules! count {
    ($($x:expr),*) => {
        0 $(+ { let _ = $x; 1 })*
    };
}

fn main() {
    println!("{}", count!(10, 20, 30));
}

Associated Types

15.

What does this print?

trait Stack {
    type Item;
    fn push(&mut self, item: Self::Item);
    fn pop(&mut self) -> Option<Self::Item>;
}

struct IntStack {
    items: Vec<i32>,
}

impl Stack for IntStack {
    type Item = i32;

    fn push(&mut self, item: i32) {
        self.items.push(item);
    }

    fn pop(&mut self) -> Option<i32> {
        self.items.pop()
    }
}

fn main() {
    let mut s = IntStack { items: vec![] };
    s.push(1);
    s.push(2);
    println!("{:?}", s.pop());
    println!("{:?}", s.pop());
    println!("{:?}", s.pop());
}
16.

Does this compile?

trait Stack {
    type Item;
    fn push(&mut self, item: Self::Item);
}

struct IntStack {
    items: Vec<i32>,
}

impl Stack for IntStack {
    fn push(&mut self, item: i32) {
        self.items.push(item);
    }
}

fn main() {
    let mut s = IntStack { items: vec![] };
    s.push(1);
}
17.

What does this print?

struct Countdown {
    current: i32,
}

impl Iterator for Countdown {
    type Item = i32;

    fn next(&mut self) -> Option<i32> {
        if self.current == 0 {
            None
        } else {
            self.current -= 1;
            Some(self.current + 1)
        }
    }
}

fn main() {
    let countdown = Countdown { current: 3 };
    for n in countdown {
        println!("{n}");
    }
}
18.

Evens is an Iterator, so every method Iterator provides, such as .sum(), already works on it. What does this print?

struct Evens {
    current: i32,
    max: i32,
}

impl Iterator for Evens {
    type Item = i32;

    fn next(&mut self) -> Option<i32> {
        if self.current > self.max {
            None
        } else {
            let value = self.current;
            self.current += 2;
            Some(value)
        }
    }
}

fn main() {
    let evens = Evens { current: 0, max: 6 };
    let total: i32 = evens.sum();
    println!("{total}");
}
19.

What does this print?

struct Evens {
    current: i32,
    max: i32,
}

impl Iterator for Evens {
    type Item = i32;

    fn next(&mut self) -> Option<i32> {
        if self.current > self.max {
            None
        } else {
            let value = self.current;
            self.current += 2;
            Some(value)
        }
    }
}

fn main() {
    let evens = Evens { current: 0, max: 6 };
    for n in evens {
        println!("{n}");
    }
}
20.

Self::Item in the trait's own return type became String once the impl chose it. What does this print?

trait Container {
    type Item;
    fn get(&self, index: usize) -> Option<&Self::Item>;
}

struct Playlist {
    songs: Vec<String>,
}

impl Container for Playlist {
    type Item = String;

    fn get(&self, index: usize) -> Option<&String> {
        self.songs.get(index)
    }
}

fn main() {
    let playlist = Playlist {
        songs: vec![String::from("one"), String::from("two")],
    };
    println!("{:?}", playlist.get(1));
    println!("{:?}", playlist.get(9));
}
21.

Does this compile?

trait Container {
    type Item;
    fn get(&self, index: usize) -> Option<&Self::Item>;
}

struct Playlist {
    songs: Vec<String>,
}

impl Container for Playlist {
    fn get(&self, index: usize) -> Option<&String> {
        self.songs.get(index)
    }
}
22.

What does this print?

trait Container {
    type Item;
    fn get(&self, index: usize) -> Option<&Self::Item>;
}

struct Numbers {
    values: Vec<i32>,
}

impl Container for Numbers {
    type Item = i32;

    fn get(&self, index: usize) -> Option<&i32> {
        self.values.get(index)
    }
}

fn main() {
    let numbers = Numbers { values: vec![10, 20, 30] };
    println!("{:?}", numbers.get(0));
    println!("{:?}", numbers.get(2));
}

Associated Types Compared with Generic Parameters

23.

What does this print?

trait Converts<T> {
    fn convert(&self) -> T;
}

struct Wrapper(i32);

impl Converts<i32> for Wrapper {
    fn convert(&self) -> i32 {
        self.0
    }
}

impl Converts<String> for Wrapper {
    fn convert(&self) -> String {
        self.0.to_string()
    }
}

fn main() {
    let w = Wrapper(9);
    let a: i32 = w.convert();
    let b: String = w.convert();
    println!("{a} {b}");
}
24.

T is part of the trait itself, so Converts<i32> and Converts<bool> count as different traits. Does this compile?

trait Converts<T> {
    fn convert(&self) -> T;
}

struct Flag(bool);

impl Converts<bool> for Flag {
    fn convert(&self) -> bool {
        self.0
    }
}

impl Converts<i32> for Flag {
    fn convert(&self) -> i32 {
        if self.0 { 1 } else { 0 }
    }
}

fn main() {
    let f = Flag(true);
    let a: bool = f.convert();
    let b: i32 = f.convert();
    println!("{a} {b}");
}
25.

Does this compile?

trait Converts {
    type Output;
    fn convert(&self) -> Self::Output;
}

struct Wrapper(i32);

impl Converts for Wrapper {
    type Output = i32;
    fn convert(&self) -> i32 {
        self.0
    }
}

impl Converts for Wrapper {
    type Output = String;
    fn convert(&self) -> String {
        self.0.to_string()
    }
}
26.

What does this print?

trait Converts {
    type Output;
    fn convert(&self) -> Self::Output;
}

struct Wrapper(i32);

impl Converts for Wrapper {
    type Output = String;

    fn convert(&self) -> String {
        self.0.to_string()
    }
}

fn main() {
    let w = Wrapper(42);
    println!("{}", w.convert());
}
27.

A type with several implementations of the same generic trait is common; From in the standard library works this way. What does this print?

trait MakesFrom<T> {
    fn make(value: T) -> Self;
}

struct Meters(f64);

impl MakesFrom<f64> for Meters {
    fn make(value: f64) -> Meters {
        Meters(value)
    }
}

impl MakesFrom<i32> for Meters {
    fn make(value: i32) -> Meters {
        Meters(value as f64)
    }
}

fn main() {
    let a = Meters::make(3.5);
    let b = Meters::make(2);
    println!("{} {}", a.0, b.0);
}
28.

Does this compile?

trait Identity {
    type Same;
    fn identity(&self) -> &Self::Same;
}

struct Value(i32);

impl Identity for Value {
    fn identity(&self) -> &i32 {
        &self.0
    }
}

fn main() {
    let v = Value(9);
    println!("{}", v.identity());
}

Operator Overloading

29.

What does this print?

use std::ops::Add;

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    type Output = Point;

    fn add(self, other: Point) -> Point {
        Point {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 3, y: 4 };
    println!("{:?}", a + b);
}
30.

What does this print?

use std::ops::Sub;

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

impl Sub for Point {
    type Output = Point;

    fn sub(self, other: Point) -> Point {
        Point {
            x: self.x - other.x,
            y: self.y - other.y,
        }
    }
}

fn main() {
    let a = Point { x: 5, y: 7 };
    let b = Point { x: 2, y: 3 };
    println!("{:?}", a - b);
}
31.

Does this compile?

use std::ops::Sub;

struct Point {
    x: i32,
    y: i32,
}

impl Sub for Point {
    fn sub(self, other: Point) -> Point {
        Point {
            x: self.x - other.x,
            y: self.y - other.y,
        }
    }
}
32.

Does this compile?

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 3, y: 4 };
    println!("{:?}", a + b);
}
33.

-a calls neg, the trait behind unary minus. What does this print?

use std::ops::Neg;

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

impl Neg for Point {
    type Output = Point;

    fn neg(self) -> Point {
        Point { x: -self.x, y: -self.y }
    }
}

fn main() {
    let a = Point { x: 5, y: -7 };
    println!("{:?}", -a);
}
34.

== calls eq, from PartialEq, the same way + calls add. What does this print?

#[derive(Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

impl PartialEq for Point {
    fn eq(&self, other: &Point) -> bool {
        self.x == other.x && self.y == other.y
    }
}

fn main() {
    let a = Point { x: 5, y: 7 };
    let b = Point { x: 2, y: 3 };
    println!("{}", a == b);
    println!("{}", a == Point { x: 5, y: 7 });
}
35.

Does this compile?

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 1, y: 2 };
    println!("{}", a == b);
}
36.

What does this print?

use std::ops::Add;

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    type Output = Point;

    fn add(self, other: Point) -> Point {
        Point {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

fn main() {
    let a = Point { x: 1, y: 1 };
    let b = Point { x: 2, y: 2 };
    let c = Point { x: 3, y: 3 };
    println!("{:?}", a + b + c);
}

Mixed Review

37.

What does this print?

use std::ops::Add;

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    type Output = Point;

    fn add(self, other: Point) -> Point {
        Point {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

macro_rules! point {
    ($x:expr, $y:expr) => {
        Point { x: $x, y: $y }
    };
}

fn main() {
    println!("{:?}", point!(1, 2) + point!(3, 4));
}
38.

What does this print?

struct Evens {
    current: i32,
    max: i32,
}

impl Iterator for Evens {
    type Item = i32;

    fn next(&mut self) -> Option<i32> {
        if self.current > self.max {
            None
        } else {
            let value = self.current;
            self.current += 2;
            Some(value)
        }
    }
}

macro_rules! sum_of {
    ($iter:expr) => {{
        let mut total = 0;
        for value in $iter {
            total += value;
        }
        total
    }};
}

fn main() {
    let evens = Evens { current: 0, max: 4 };
    println!("{}", sum_of!(evens));
}
39.

Does this compile?

trait Shape {
    type Unit;
    fn area(&self) -> Self::Unit;
}

struct Square {
    side: i32,
}

impl Shape for Square {
    type Unit = i32;

    fn area(&self) -> i32 {
        self.side * self.side
    }
}

impl Shape for Square {
    type Unit = f64;

    fn area(&self) -> f64 {
        (self.side * self.side) as f64
    }
}
40.

$f:expr can match a function name, not just a value. What does this print?

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

macro_rules! apply_twice {
    ($f:expr, $x:expr) => {
        $f($f($x))
    };
}

fn main() {
    println!("{}", apply_twice!(double, 3));
}
41.

What does this print?

trait Container {
    type Item;
    fn get(&self, index: usize) -> Option<&Self::Item>;
}

struct Numbers {
    values: Vec<i32>,
}

impl Container for Numbers {
    type Item = i32;

    fn get(&self, index: usize) -> Option<&i32> {
        self.values.get(index)
    }
}

macro_rules! describe_get {
    ($container:expr, $index:expr) => {
        match $container.get($index) {
            Some(value) => format!("found {value}"),
            None => String::from("missing"),
        }
    };
}

fn main() {
    let numbers = Numbers { values: vec![10, 20] };
    println!("{}", describe_get!(numbers, 0));
    println!("{}", describe_get!(numbers, 5));
}
42.

What does this print?

use std::ops::Add;

#[derive(Debug, Clone, Copy)]
struct Meters(i32);

impl Add for Meters {
    type Output = Meters;

    fn add(self, other: Meters) -> Meters {
        Meters(self.0 + other.0)
    }
}

struct Trip {
    current: Meters,
    remaining: i32,
}

impl Iterator for Trip {
    type Item = Meters;

    fn next(&mut self) -> Option<Meters> {
        if self.remaining == 0 {
            None
        } else {
            self.remaining -= 1;
            self.current = self.current + Meters(10);
            Some(self.current)
        }
    }
}

fn main() {
    let trip = Trip { current: Meters(0), remaining: 3 };
    for distance in trip {
        println!("{:?}", distance);
    }
}