What does this print?
fn identity<T>(x: T) -> T {
x
}
fn main() {
println!("{}", identity(5));
println!("{}", identity("hi"));
}Running it prints:
5 hi
Practice 11
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.
0 of 50 answered·0 correct
What does this print?
fn identity<T>(x: T) -> T {
x
}
fn main() {
println!("{}", identity(5));
println!("{}", identity("hi"));
}Running it prints:
5 hi
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));
}Running it prints:
4 1.5
Does this compile?
fn bigger<T>(a: T, b: T) -> T {
if a > b { a } else { b }
}
fn main() {
println!("{}", bigger(4, 9));
}The compiler says:
error[E0369]: binary operation `>` cannot be applied to type `T`
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);
}Running it prints:
1 and "one" false and 2.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));
}The compiler says:
error[E0277]: the trait bound `String: Copy` is not satisfied
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));
}Running it prints:
z
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');
}Running it prints:
10 and 20 "x" and "y" 3.5 and 'z'
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));
}Running it prints:
3
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));
}Running it prints:
9 2.2 k
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);
}Running it prints:
4 9
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);
}Running it prints:
up down
Does this compile?
struct Pair<T> {
first: T,
second: T,
}
fn main() {
let p = Pair { first: 4, second: "nine" };
println!("{} {}", p.first, p.second);
}The compiler says:
error[E0308]: mismatched types
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);
}Running it prints:
temp: 72
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);
}Running it prints:
2 7
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());
}Running it prints:
3 then 8
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"),
}
}Running it prints:
half is 4 odd number
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}"),
}
}Running it prints:
one: 5 two: 3 9
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());
}Running it prints:
hello, Ana
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());
}Running it prints:
hello, Ana unit 7 online
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);
}Running it prints:
hello, Ana
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);
}Running it prints:
unit 3 online
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);
}The compiler says:
error[E0599]: no method named `greet` found for reference `&T` in the current scope
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);
}Running it prints:
hello, Ana
Person { name: "Ana" }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());
}Running it prints:
hello, Ana (10)
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);
}Running it prints:
hello, Ana bye, Ana
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());
}Running it prints:
20
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);
}
}Running it prints:
hello, Ana hello, Bo
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());
}Running it prints:
hello, Ana
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());
}Running it prints:
BEEP unit 7
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());
}Running it prints:
hello, Ana BEEP unit 4
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());
}Running it prints:
hi Ana, nice to meet you
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());
}The compiler says:
error[E0046]: not all trait items implemented, missing: `name`
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());
}Running it prints:
BEEP unit 2, nice to meet you
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());
}Running it prints:
true false
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);
}Running it prints:
passed with 88
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());
}Running it prints:
now arriving: Red Line
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());
}The compiler says:
error[E0277]: `Train` doesn't implement `std::fmt::Display` error[E0277]: `Train` doesn't implement `std::fmt::Display`
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());
}Running it prints:
now arriving: Blue Line
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());
}Running it prints:
BUS: route 12
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());
}Running it prints:
now arriving: Red Line BUS: route 4
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);
}Running it prints:
now arriving: Green Line
dyn TraitOne 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());
}
}Running it prints:
hello, Ana unit 7 online
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 }];
}The compiler says:
error[E0308]: mismatched types
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);
}Running it prints:
hello, Ana
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);
}Running it prints:
hello, Ana hello, Ana
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);
}The compiler says:
error[E0609]: no field `name` on type `&dyn Greet`
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());
}
}Running it prints:
hello, Ana BEEP unit 3
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());
}
}Running it prints:
now arriving: Red Line now arriving: route 9
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));
}Running it prints:
area 9 rectangle, area 10 total 19
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);
}
}Running it prints:
4 16