Activity 30: Generics
Name:
Problem 1 we'll do together in lecture. Problems 2 to 5 run right here on the website: edit the code in the box, press the play button in its corner, read the error, and fix it. Don't refresh the page, or your edits will disappear.
Write your answers on the sheet and hand it in on your way out.
Problem 1: keep both (in lecture)
Our max takes ownership of both arguments. After max(a, b) with two strings, a and b are moved and we can't use them again.
fn max<T: PartialOrd>(x: T, y: T) -> T {
if x > y { x } else { y }
}
Rewrite max so the caller keeps a and b, and still gets back a T of its own. Hint: T: PartialOrd + Debug asks for two traits at once.
Problems 2 to 5 are on the laptop. For 2, 3, and 4, write the first line of the function once it compiled.
Problem 2. print_twice
Problem 3. is_greater
Problem 4. compare_and_print
Problem 5. Once it runs, add println!("{:?}", pair); as the last line of main. Does it compile? What does the compiler say, in a few words?
Problem 2: print it twice (together)
Add the bound that makes this compile. If you write just Debug, the compiler will ask for one more line.
fn print_twice<T>(value: T) { println!("{:?}", value); println!("{:?}", value); } fn main() { print_twice(42); print_twice("hello"); }
Problem 3: comparing
Same idea. Read the help: line before you fix it. It's most of the answer.
fn is_greater<T>(a: T, b: T) -> bool { a > b } fn main() { println!("{}", is_greater(5, 3)); println!("{}", is_greater(2.5, 7.8)); println!("{}", is_greater("pear", "apple")); }
Problem 4: two bounds at once
This function compares and prints, so one bound isn't enough.
fn compare_and_print<T>(a: T, b: T) { if a > b { println!("{:?} is greater", a); } else if a == b { println!("They're equal!"); } else { println!("{:?} is greater", b); } } fn main() { compare_and_print(5, 3); compare_and_print(2.5, 7.8); compare_and_print('q', 'q'); }
Problem 5: a generic pair
A Pair<T> holds two values of the same type. Fill in both todo!() lines.
#[derive(Debug)] struct Pair<T> { first: T, second: T, } impl<T> Pair<T> { // 1. Build a Pair. fn new(first: T, second: T) -> Pair<T> { todo!() } // 2. Return a new Pair with the two values traded. fn swap(self) -> Pair<T> { todo!() } } fn main() { let pair = Pair::new(5, 10); println!("Original: {:?}", pair); // Pair { first: 5, second: 10 } let swapped = pair.swap(); println!("Swapped: {:?}", swapped); // Pair { first: 10, second: 5 } let words = Pair::new("left", "right"); println!("{:?}", words.swap()); // Pair { first: "right", second: "left" } }
Once it runs, add println!("{:?}", pair); as the last line of main. Does it compile? Write what the compiler says on your sheet.
If you finish early
Two different types. Give Pair a second type parameter, so the two values can be different types. Look at what swap returns.
#[derive(Debug)] struct Pair<T, U> { first: T, second: U, } impl<T, U> Pair<T, U> { fn new(first: T, second: U) -> Pair<T, U> { todo!() } fn swap(self) -> Pair<U, T> { todo!() } } fn main() { let mixed = Pair::new(42, "hello"); // Pair<i32, &str> let swapped = mixed.swap(); // what type is this? println!("{:?}", swapped); }
Your own Option. Write a generic enum Maybe<T> with two variants, Just(T) and Nothing, and give it two methods. main is written for you. It won't compile until Maybe exists.
// 1. Write the enum: Maybe<T>, with variants Just(T) and Nothing. // 2. Write an impl block for it with two methods: // is_just(&self) -> bool // unwrap_or(self, fallback: T) -> T fn main() { let found = Maybe::Just(3); let missing: Maybe<i32> = Maybe::Nothing; println!("{}", found.is_just()); // true println!("{}", missing.is_just()); // false println!("{}", found.unwrap_or(0)); // 3 println!("{}", missing.unwrap_or(0)); // 0 }
Solutions
- P1:
fn max<T: PartialOrd + Clone>(x: &T, y: &T) -> T { if x > y { x.clone() } else { y.clone() } }, called asmax(&a, &b). Three changes:&T,.clone(),+ Clone. - P2:
fn print_twice<T: Debug>(value: T)plususe std::fmt::Debug;at the top.T: std::fmt::Debugwith nousealso works - P3:
fn is_greater<T: PartialOrd>(a: T, b: T) -> bool - P4:
fn compare_and_print<T: PartialOrd + Debug>(a: T, b: T)plus theuse. - P5: No.
swaptakesself, sopairwas moved. "borrow of moved value:pair"
Problem 5:
#![allow(unused)] fn main() { impl<T> Pair<T> { fn new(first: T, second: T) -> Pair<T> { Pair { first, second } } fn swap(self) -> Pair<T> { Pair { first: self.second, second: self.first } } } }
Finish-early:
#![allow(unused)] fn main() { // Pair<T, U> fn new(first: T, second: U) -> Pair<T, U> { Pair { first, second } } fn swap(self) -> Pair<U, T> { Pair { first: self.second, second: self.first } } // swapped is Pair<&str, i32> // Maybe<T> enum Maybe<T> { Just(T), Nothing, } impl<T> Maybe<T> { fn is_just(&self) -> bool { match self { Maybe::Just(_) => true, Maybe::Nothing => false, } } fn unwrap_or(self, fallback: T) -> T { match self { Maybe::Just(value) => value, Maybe::Nothing => fallback, } } } }