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);
}Running it prints:
rupee 1
Practice 09
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.
0 of 50 answered·0 correct
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);
}Running it prints:
rupee 1
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);
}Running it prints:
7
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);
}The compiler says:
error[E0594]: cannot assign to `c.total`, as `c` is not declared as mutable
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);
}Running it prints:
Kiran 40
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);
}Running it prints:
Kiran 55
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:#?}");
}Running it prints:
Box2 { width: 3, height: 4 }
Box2 {
width: 3,
height: 4,
}Does this compile?
struct Box2 {
width: u32,
height: u32,
}
fn main() {
let b = Box2 { width: 3, height: 4 };
println!("{}", b);
}The compiler says:
error[E0277]: `Box2` doesn't implement `std::fmt::Display`
What does this print?
struct Pair(i32, i32);
fn main() {
let p = Pair(10, -3);
println!("{} {}", p.0, p.1);
}Running it prints:
10 -3
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);
}The compiler says:
error[E0382]: borrow of moved value: `first.name`
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);
}Running it prints:
Wei 12
impl BlocksWhat 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());
}Running it prints:
18
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);
}Running it prints:
7
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);
}The compiler says:
error[E0382]: borrow of moved value: `t`
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());
}Running it prints:
25
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);
}The compiler says:
error[E0423]: expected value, found struct `Rect`
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));
}Running it prints:
10 15
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());
}Running it prints:
-30 true
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());
}Running it prints:
big
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());
}Running it prints:
6 12
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());
}
}Running it prints:
Asha true Bo false Cy true
matchWhat 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"),
}
}Running it prints:
go
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));
}Running it prints:
16
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));
}The compiler says:
error[E0004]: non-exhaustive patterns: `Light::Yellow` not covered
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}");
}Running it prints:
50
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));
}
}Running it prints:
12 0 9
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}"),
}
}Running it prints:
Wei retired in 2019
What does this print?
#[derive(Debug)]
enum Status {
Active,
Retired(u32),
}
fn main() {
let s = Status::Retired(2019);
println!("{s:?}");
}Running it prints:
Retired(2019)
Does this compile?
enum Status {
Active,
Retired(u32),
}
fn main() {
let s = Status::Active;
println!("{s:?}");
}The compiler says:
error[E0277]: `Status` doesn't implement `Debug`
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));
}Running it prints:
big circle
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}");
}Running it prints:
7
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));
}The compiler says:
error[E0004]: non-exhaustive patterns: `Coin::Dime` not covered
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);
}
}Running it prints:
Asha pass Bo fail
if let and while letWhat 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"),
}
}Running it prints:
odd
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));
}Running it prints:
88 0
What does this print?
fn main() {
let town: Option<String> = None;
if let Some(name) = town {
println!("town is {name}");
} else {
println!("no town");
}
}Running it prints:
no town
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");
}Running it prints:
count is 3 done
What does this print?
fn main() {
let mut queue = vec!["a", "b", "c"];
while let Some(item) = queue.pop() {
println!("{item}");
}
println!("empty");
}Running it prints:
c b a empty
What does this print?
fn main() {
let name: Option<String> = Some(String::from("Lima"));
println!("{}", name.unwrap_or(String::from("unknown")));
}Running it prints:
Lima
Does this compile?
fn main() {
let count: Option<i32> = Some(4);
let total = count + 1;
println!("{total}");
}The compiler says:
error[E0369]: cannot add `{integer}` to `Option<i32>`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");
}
}
}Running it prints:
4 halves to 2 7 is odd 10 halves to 5
panic! and the ? OperatorWhat 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}"),
}
}Running it prints:
answer: 3
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}"),
}
}
}Running it prints:
answer: 4 failed: cannot divide by zero
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));
}Running it prints:
left: 150
Then it panics: asked for 900 but the balance is only 200
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}");
}Running it prints:
13
Then it panics: called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }
"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}");
}Running it prints nothing.
Then it panics: not a whole number: ParseIntError { kind: InvalidDigit }
What does this print?
fn main() {
let text = "56";
let number: i32 = text.parse().unwrap();
println!("{}", number + 4);
}Running it prints:
60
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}"),
}
}Running it prints:
total: 24 failed: invalid digit found in string
? 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(""));
}Running it prints:
Some('D')
NoneA 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");
}Running it prints:
Tokyo is cold Cairo is hot bad line: Perth mild
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());
}
}Running it prints:
queued running at 40% done, ok done, error 2