What does this print?
macro_rules! cube {
($x:expr) => {
$x * $x * $x
};
}
fn main() {
println!("{}", cube!(3));
}Running it prints:
27
Practice 16
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.
0 of 42 answered·0 correct
macro_rules!What does this print?
macro_rules! cube {
($x:expr) => {
$x * $x * $x
};
}
fn main() {
println!("{}", cube!(3));
}Running it prints:
27
What does this print?
macro_rules! announce {
($x:expr, $y:expr) => {
format!("{} and {}", $x, $y)
};
}
fn main() {
println!("{}", announce!("cats", "dogs"));
}Running it prints:
cats and dogs
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));
}Running it prints:
12
greet! only matches an empty argument list. Does this compile?
macro_rules! greet {
() => {
println!("hi");
};
}
fn main() {
greet!(5);
}The compiler says:
error: no rules expected `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
};
}The compiler says:
error: cannot find macro `triple` in this scope
What does this print?
macro_rules! greet {
() => {
println!("hello from a macro");
};
}
fn main() {
greet!();
greet!();
}Running it prints:
hello from a macro hello from a macro
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));
}Running it prints:
7 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));
}Running it prints:
nothing one: 5 two: 5 and 6
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));
}The compiler says:
error: no rules expected `,`
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));
}Running it prints:
hi! hi!!!
What does this print?
macro_rules! sum {
($($x:expr),*) => {{
let mut total = 0;
$(total += $x;)*
total
}};
}
fn main() {
println!("{}", sum!(1, 2, 3, 4));
}Running it prints:
10
What does this print?
macro_rules! product {
($($x:expr),*) => {{
let mut total = 1;
$(total *= $x;)*
total
}};
}
fn main() {
println!("{}", product!(2, 3, 4));
}Running it prints:
24
$(...),* 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!());
}Running it prints:
0
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));
}Running it prints:
3
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());
}Running it prints:
Some(2) Some(1) None
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);
}The compiler says:
error[E0046]: not all trait items implemented, missing: `Item`
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}");
}
}Running it prints:
3 2 1
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}");
}Running it prints:
12
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}");
}
}Running it prints:
0 2 4 6
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));
}Running it prints:
Some("two")
NoneDoes 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)
}
}The compiler says:
error[E0046]: not all trait items implemented, missing: `Item`
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));
}Running it prints:
Some(10) Some(30)
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}");
}Running it prints:
9 9
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}");
}Running it prints:
true 1
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()
}
}The compiler says:
error[E0119]: conflicting implementations of trait `Converts` for type `Wrapper`
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());
}Running it prints:
42
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);
}Running it prints:
3.5 2
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());
}The compiler says:
error[E0046]: not all trait items implemented, missing: `Same`
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);
}Running it prints:
Point { x: 4, y: 6 }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);
}Running it prints:
Point { x: 3, y: 4 }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,
}
}
}The compiler says:
error[E0046]: not all trait items implemented, missing: `Output`
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);
}The compiler says:
error[E0369]: cannot add `Point` to `Point`
-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);
}Running it prints:
Point { x: -5, y: 7 }== 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 });
}Running it prints:
false true
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);
}The compiler says:
error[E0369]: binary operation `==` cannot be applied to type `Point`
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);
}Running it prints:
Point { x: 6, y: 6 }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));
}Running it prints:
Point { x: 4, y: 6 }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));
}Running it prints:
6
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
}
}The compiler says:
error[E0119]: conflicting implementations of trait `Shape` for type `Square`
$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));
}Running it prints:
12
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));
}Running it prints:
found 10 missing
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);
}
}Running it prints:
Meters(10) Meters(20) Meters(30)