Practice 11

Generics and 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 11.

Course

0 of 50 answered·0 correct

Generic Functions

1.

What does this print?

fn identity<T>(x: T) -> T {
    x
}

fn main() {
    println!("{}", identity(5));
    println!("{}", identity("hi"));
}
2.

What does this print?

fn smaller<T: PartialOrd>(a: T, b: T) -> T {
    if a < b { a } else { b }
}

fn main() {
    println!("{}", smaller(4, 9));
    println!("{}", smaller(2.5, 1.5));
}
3.

Does this compile?

fn bigger<T>(a: T, b: T) -> T {
    if a > b { a } else { b }
}

fn main() {
    println!("{}", bigger(4, 9));
}
4.

What does this print?

fn show_pair<A: std::fmt::Debug, B: std::fmt::Debug>(a: A, b: B) {
    println!("{a:?} and {b:?}");
}

fn main() {
    show_pair(1, "one");
    show_pair(false, 2.5);
}
5.

Does this compile?

fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];
    for &item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn main() {
    let words = vec![String::from("pear"), String::from("apple")];
    println!("{}", largest(&words));
}
6.

The same function, called on char instead of String. What does this print?

fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];
    for &item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn main() {
    let letters = ['m', 'a', 'z', 'q'];
    println!("{}", largest(&letters));
}
7.

What does this print?

fn describe_pair<A: std::fmt::Debug, B: std::fmt::Debug>(a: A, b: B) {
    println!("{a:?} and {b:?}");
}

fn main() {
    describe_pair(10, 20);
    describe_pair("x", "y");
    describe_pair(3.5, 'z');
}
8.

The bound is written with where here instead of inside the angle brackets. What does this print?

fn smaller<T>(a: T, b: T) -> T
where
    T: PartialOrd,
{
    if a < b { a } else { b }
}

fn main() {
    println!("{}", smaller(10, 3));
}
9.

This calls largest with three different types. What does it print?

fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];
    for &item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn main() {
    let a = [3, 9, 1];
    let b = [1.1, 0.4, 2.2];
    let c = ['d', 'b', 'k'];
    println!("{}", largest(&a));
    println!("{}", largest(&b));
    println!("{}", largest(&c));
}

Generic Structs and Enums

10.

What does this print?

struct Pair<T> {
    first: T,
    second: T,
}

fn main() {
    let p = Pair { first: 4, second: 9 };
    println!("{} {}", p.first, p.second);
}
11.

The same struct, holding String instead of i32. What does this print?

struct Pair<T> {
    first: T,
    second: T,
}

fn main() {
    let p = Pair { first: String::from("up"), second: String::from("down") };
    println!("{} {}", p.first, p.second);
}
12.

Does this compile?

struct Pair<T> {
    first: T,
    second: T,
}

fn main() {
    let p = Pair { first: 4, second: "nine" };
    println!("{} {}", p.first, p.second);
}
13.

label is always a String, and only value changes type. What does this print?

struct Labeled<T> {
    label: String,
    value: T,
}

fn main() {
    let temp = Labeled { label: String::from("temp"), value: 72 };
    println!("{}: {}", temp.label, temp.value);
}
14.

What does this print?

struct Pair<T> {
    first: T,
    second: T,
}

impl<T> Pair<T> {
    fn new(first: T, second: T) -> Pair<T> {
        Pair { first, second }
    }
}

fn main() {
    let p = Pair::new(2, 7);
    println!("{} {}", p.first, p.second);
}
15.

What does this print?

struct Pair<T> {
    first: T,
    second: T,
}

impl<T: std::fmt::Display> Pair<T> {
    fn describe(&self) -> String {
        format!("{} then {}", self.first, self.second)
    }
}

fn main() {
    let p = Pair { first: 3, second: 8 };
    println!("{}", p.describe());
}
16.

Option<T> is a generic enum from the standard library. What does this print?

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

fn main() {
    match halve(8) {
        Some(v) => println!("half is {v}"),
        None => println!("odd number"),
    }
    match halve(7) {
        Some(v) => println!("half is {v}"),
        None => println!("odd number"),
    }
}
17.

A generic enum you wrote yourself. What does this print?

enum Holder<T> {
    One(T),
    Two(T, T),
}

fn main() {
    let a = Holder::One(5);
    let b = Holder::Two(3, 9);

    match a {
        Holder::One(x) => println!("one: {x}"),
        Holder::Two(x, y) => println!("two: {x} {y}"),
    }
    match b {
        Holder::One(x) => println!("one: {x}"),
        Holder::Two(x, y) => println!("two: {x} {y}"),
    }
}

Traits

18.

What does this print?

trait Greet {
    fn greet(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

fn main() {
    let p = Person { name: String::from("Ana") };
    println!("{}", p.greet());
}
19.

A second type implements the same trait, with its own method body. What does this print?

trait Greet {
    fn greet(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

struct Robot {
    id: u32,
}

impl Greet for Robot {
    fn greet(&self) -> String {
        format!("unit {} online", self.id)
    }
}

fn main() {
    let p = Person { name: String::from("Ana") };
    let r = Robot { id: 7 };
    println!("{}", p.greet());
    println!("{}", r.greet());
}
20.

announce takes a trait bound instead of naming Person directly. What does this print?

trait Greet {
    fn greet(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

fn announce<T: Greet>(item: &T) {
    println!("{}", item.greet());
}

fn main() {
    let p = Person { name: String::from("Ana") };
    announce(&p);
}
21.

The same bound, written with where. What does this print?

trait Greet {
    fn greet(&self) -> String;
}

struct Robot {
    id: u32,
}

impl Greet for Robot {
    fn greet(&self) -> String {
        format!("unit {} online", self.id)
    }
}

fn announce<T>(item: &T)
where
    T: Greet,
{
    println!("{}", item.greet());
}

fn main() {
    let r = Robot { id: 3 };
    announce(&r);
}
22.

Does this compile?

trait Greet {
    fn greet(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

fn announce<T>(item: &T) {
    println!("{}", item.greet());
}

fn main() {
    let p = Person { name: String::from("Ana") };
    announce(&p);
}
23.

Two bounds, joined with +. What does this print?

use std::fmt::Debug;

trait Greet {
    fn greet(&self) -> String;
}

#[derive(Debug)]
struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

fn announce<T: Greet + Debug>(item: &T) {
    println!("{}", item.greet());
    println!("{item:?}");
}

fn main() {
    let p = Person { name: String::from("Ana") };
    announce(&p);
}
24.

A trait method's return value used like any other String. What does this print?

trait Greet {
    fn greet(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

fn main() {
    let p = Person { name: String::from("Ana") };
    let message = p.greet();
    println!("{} ({})", message, message.len());
}
25.

One type implements two different traits, and visit requires both. What does this print?

trait Greet {
    fn greet(&self) -> String;
}

trait Farewell {
    fn farewell(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

impl Farewell for Person {
    fn farewell(&self) -> String {
        format!("bye, {}", self.name)
    }
}

fn visit<T: Greet + Farewell>(item: &T) {
    println!("{}", item.greet());
    println!("{}", item.farewell());
}

fn main() {
    let p = Person { name: String::from("Ana") };
    visit(&p);
}
26.

What does this print?

trait Area {
    fn area(&self) -> u32;
}

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

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

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

announce is called once for each Person in the array. What does this print?

trait Greet {
    fn greet(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

fn announce<T: Greet>(item: &T) {
    println!("{}", item.greet());
}

fn main() {
    let people = [
        Person { name: String::from("Ana") },
        Person { name: String::from("Bo") },
    ];
    for p in &people {
        announce(p);
    }
}

Default Implementations

28.

greet has a default body in the trait, and Person does not write its own. What does this print?

trait Greet {
    fn name(&self) -> String;

    fn greet(&self) -> String {
        format!("hello, {}", self.name())
    }
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn name(&self) -> String {
        self.name.clone()
    }
}

fn main() {
    let p = Person { name: String::from("Ana") };
    println!("{}", p.greet());
}
29.

Here Robot writes its own greet, instead of using the default. What does this print?

trait Greet {
    fn name(&self) -> String;

    fn greet(&self) -> String {
        format!("hello, {}", self.name())
    }
}

struct Robot {
    id: u32,
}

impl Greet for Robot {
    fn name(&self) -> String {
        format!("unit {}", self.id)
    }

    fn greet(&self) -> String {
        format!("BEEP {}", self.name())
    }
}

fn main() {
    let r = Robot { id: 7 };
    println!("{}", r.greet());
}
30.

Person uses the default greet. Robot overrides it. What does this print?

trait Greet {
    fn name(&self) -> String;

    fn greet(&self) -> String {
        format!("hello, {}", self.name())
    }
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn name(&self) -> String {
        self.name.clone()
    }
}

struct Robot {
    id: u32,
}

impl Greet for Robot {
    fn name(&self) -> String {
        format!("unit {}", self.id)
    }

    fn greet(&self) -> String {
        format!("BEEP {}", self.name())
    }
}

fn main() {
    let p = Person { name: String::from("Ana") };
    let r = Robot { id: 4 };
    println!("{}", p.greet());
    println!("{}", r.greet());
}
31.

One default method calls another default method of the same trait. What does this print?

trait Greet {
    fn name(&self) -> String;

    fn short_greet(&self) -> String {
        format!("hi {}", self.name())
    }

    fn greet(&self) -> String {
        format!("{}, nice to meet you", self.short_greet())
    }
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn name(&self) -> String {
        self.name.clone()
    }
}

fn main() {
    let p = Person { name: String::from("Ana") };
    println!("{}", p.greet());
}
32.

name has no default body in the trait. Does this compile?

trait Greet {
    fn name(&self) -> String;

    fn greet(&self) -> String {
        format!("hello, {}", self.name())
    }
}

struct Person {
    name: String,
}

impl Greet for Person {}

fn main() {
    let p = Person { name: String::from("Ana") };
    println!("{}", p.greet());
}
33.

Robot overrides short_greet but not greet. What does this print?

trait Greet {
    fn name(&self) -> String;

    fn short_greet(&self) -> String {
        format!("hi {}", self.name())
    }

    fn greet(&self) -> String {
        format!("{}, nice to meet you", self.short_greet())
    }
}

struct Robot {
    id: u32,
}

impl Greet for Robot {
    fn name(&self) -> String {
        format!("unit {}", self.id)
    }

    fn short_greet(&self) -> String {
        format!("BEEP {}", self.name())
    }
}

fn main() {
    let r = Robot { id: 2 };
    println!("{}", r.greet());
}
34.

passed is a default method that calls the required method score. What does this print?

trait Scored {
    fn score(&self) -> u32;

    fn passed(&self) -> bool {
        self.score() >= 50
    }
}

struct Student {
    marks: u32,
}

impl Scored for Student {
    fn score(&self) -> u32 {
        self.marks
    }
}

fn main() {
    let a = Student { marks: 72 };
    let b = Student { marks: 40 };
    println!("{}", a.passed());
    println!("{}", b.passed());
}
35.

report takes a trait bound and calls the default method passed on it. What does this print?

trait Scored {
    fn score(&self) -> u32;

    fn passed(&self) -> bool {
        self.score() >= 50
    }
}

struct Student {
    marks: u32,
}

impl Scored for Student {
    fn score(&self) -> u32 {
        self.marks
    }
}

fn report<T: Scored>(item: &T) {
    if item.passed() {
        println!("passed with {}", item.score());
    } else {
        println!("failed with {}", item.score());
    }
}

fn main() {
    let a = Student { marks: 88 };
    report(&a);
}

Supertraits

36.

Announce requires Display as a supertrait, and its default body writes {self} directly. What does this print?

use std::fmt::Display;

trait Announce: Display {
    fn announce(&self) -> String {
        format!("now arriving: {self}")
    }
}

struct Train {
    line: String,
}

impl Display for Train {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.line)
    }
}

impl Announce for Train {}

fn main() {
    let t = Train { line: String::from("Red Line") };
    println!("{}", t.announce());
}
37.

The same trait, but Train never implements Display. Does this compile?

trait Announce: std::fmt::Display {
    fn announce(&self) -> String {
        format!("now arriving: {self}")
    }
}

struct Train {
    line: String,
}

impl Announce for Train {}

fn main() {
    let t = Train { line: String::from("Red Line") };
    println!("{}", t.announce());
}
38.

The supertrait here, Named, is a trait you wrote yourself, not one from the standard library. What does this print?

trait Named {
    fn name(&self) -> String;
}

trait Announce: Named {
    fn announce(&self) -> String {
        format!("now arriving: {}", self.name())
    }
}

struct Train {
    line: String,
}

impl Named for Train {
    fn name(&self) -> String {
        self.line.clone()
    }
}

impl Announce for Train {}

fn main() {
    let t = Train { line: String::from("Blue Line") };
    println!("{}", t.announce());
}
39.

Bus overrides announce instead of using the default. What does this print?

trait Named {
    fn name(&self) -> String;
}

trait Announce: Named {
    fn announce(&self) -> String {
        format!("now arriving: {}", self.name())
    }
}

struct Bus {
    route: u32,
}

impl Named for Bus {
    fn name(&self) -> String {
        format!("route {}", self.route)
    }
}

impl Announce for Bus {
    fn announce(&self) -> String {
        format!("BUS: {}", self.name())
    }
}

fn main() {
    let b = Bus { route: 12 };
    println!("{}", b.announce());
}
40.

Both types implement Named and Announce. Train keeps the default announce, Bus overrides it. What does this print?

trait Named {
    fn name(&self) -> String;
}

trait Announce: Named {
    fn announce(&self) -> String {
        format!("now arriving: {}", self.name())
    }
}

struct Train {
    line: String,
}

impl Named for Train {
    fn name(&self) -> String {
        self.line.clone()
    }
}

impl Announce for Train {}

struct Bus {
    route: u32,
}

impl Named for Bus {
    fn name(&self) -> String {
        format!("route {}", self.route)
    }
}

impl Announce for Bus {
    fn announce(&self) -> String {
        format!("BUS: {}", self.name())
    }
}

fn main() {
    let t = Train { line: String::from("Red Line") };
    let b = Bus { route: 4 };
    println!("{}", t.announce());
    println!("{}", b.announce());
}
41.

welcome takes a bound of Announce, which already requires Named. What does this print?

trait Named {
    fn name(&self) -> String;
}

trait Announce: Named {
    fn announce(&self) -> String {
        format!("now arriving: {}", self.name())
    }
}

struct Train {
    line: String,
}

impl Named for Train {
    fn name(&self) -> String {
        self.line.clone()
    }
}

impl Announce for Train {}

fn welcome<T: Announce>(item: &T) {
    println!("{}", item.announce());
}

fn main() {
    let t = Train { line: String::from("Green Line") };
    welcome(&t);
}

Trait Objects and dyn Trait

42.

One Vec holds a Person and a Robot together, behind Box<dyn Greet>. What does this print?

trait Greet {
    fn greet(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

struct Robot {
    id: u32,
}

impl Greet for Robot {
    fn greet(&self) -> String {
        format!("unit {} online", self.id)
    }
}

fn main() {
    let items: Vec<Box<dyn Greet>> = vec![
        Box::new(Person { name: String::from("Ana") }),
        Box::new(Robot { id: 7 }),
    ];

    for item in &items {
        println!("{}", item.greet());
    }
}
43.

This Vec has no dyn anywhere. Does it compile?

struct Person {
    name: String,
}

struct Robot {
    id: u32,
}

fn main() {
    let items = vec![Person { name: String::from("Ana") }, Robot { id: 7 }];
}
44.

announce takes &dyn Greet directly, with no Box. What does this print?

trait Greet {
    fn greet(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

fn announce(item: &dyn Greet) {
    println!("{}", item.greet());
}

fn main() {
    let p = Person { name: String::from("Ana") };
    announce(&p);
}
45.

announce_generic uses a trait bound. announce_dyn uses dyn Greet. What does this print?

trait Greet {
    fn greet(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

fn announce_generic<T: Greet>(item: &T) {
    println!("{}", item.greet());
}

fn announce_dyn(item: &dyn Greet) {
    println!("{}", item.greet());
}

fn main() {
    let p = Person { name: String::from("Ana") };
    announce_generic(&p);
    announce_dyn(&p);
}
46.

name is a field of Person, not a method of Greet. Does this compile?

trait Greet {
    fn greet(&self) -> String;
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) -> String {
        format!("hello, {}", self.name)
    }
}

fn announce(item: &dyn Greet) {
    println!("{}", item.name);
}

fn main() {
    let p = Person { name: String::from("Ana") };
    announce(&p);
}
47.

greet has a default body. Robot overrides it, Person does not, and both are stored in the same Vec<Box<dyn Greet>>. What does this print?

trait Greet {
    fn name(&self) -> String;

    fn greet(&self) -> String {
        format!("hello, {}", self.name())
    }
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn name(&self) -> String {
        self.name.clone()
    }
}

struct Robot {
    id: u32,
}

impl Greet for Robot {
    fn name(&self) -> String {
        format!("unit {}", self.id)
    }

    fn greet(&self) -> String {
        format!("BEEP {}", self.name())
    }
}

fn main() {
    let items: Vec<Box<dyn Greet>> = vec![
        Box::new(Person { name: String::from("Ana") }),
        Box::new(Robot { id: 3 }),
    ];

    for item in &items {
        println!("{}", item.greet());
    }
}
48.

A trait object built from a trait with a supertrait. What does this print?

use std::fmt::Display;

trait Announce: Display {
    fn announce(&self) -> String {
        format!("now arriving: {self}")
    }
}

struct Train {
    line: String,
}

impl Display for Train {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.line)
    }
}

impl Announce for Train {}

struct Bus {
    route: u32,
}

impl Display for Bus {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "route {}", self.route)
    }
}

impl Announce for Bus {}

fn main() {
    let items: Vec<Box<dyn Announce>> = vec![
        Box::new(Train { line: String::from("Red Line") }),
        Box::new(Bus { route: 9 }),
    ];

    for item in &items {
        println!("{}", item.announce());
    }
}
49.

A longer program, mixing a default method, an override, and a dyn collection. What does this print?

trait Shape {
    fn area(&self) -> u32;

    fn describe(&self) -> String {
        format!("area {}", self.area())
    }
}

struct Square {
    side: u32,
}

impl Shape for Square {
    fn area(&self) -> u32 {
        self.side * self.side
    }
}

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

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

    fn describe(&self) -> String {
        format!("rectangle, area {}", self.area())
    }
}

fn total_area(shapes: &[Box<dyn Shape>]) -> u32 {
    let mut total = 0;
    for shape in shapes {
        total += shape.area();
    }
    total
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Square { side: 3 }),
        Box::new(Rect { width: 2, height: 5 }),
    ];

    for shape in &shapes {
        println!("{}", shape.describe());
    }
    println!("total {}", total_area(&shapes));
}
50.

Every Square here is the same concrete type, so print_area uses a plain trait bound, with no dyn anywhere. What does this print?

trait Shape {
    fn area(&self) -> u32;
}

struct Square {
    side: u32,
}

impl Shape for Square {
    fn area(&self) -> u32 {
        self.side * self.side
    }
}

fn print_area<T: Shape>(shape: &T) {
    println!("{}", shape.area());
}

fn main() {
    let squares = vec![
        Square { side: 2 },
        Square { side: 4 },
    ];

    for s in &squares {
        print_area(s);
    }
}