Complete these tasks to reinforce what you learned in this module.
Write a function swap<T>(a: T, b: T) -> (T, T) that returns (b, a). Call it with two i32 values and print the tuple.
T and returns a tuple. The theory shows how to declare a generic function with angle brackets.// Task 1: Generic swap. See tasks/TASKS.md.
fn main() {
todo!("Implement swap<T> and call with 10, 20");
}
Define a struct Wrapper<T> with one field value: T. Implement Wrapper::new(value: T) -> Wrapper<T> and a method get(&self) -> &T. In main, create Wrapper::new("hello") and print the result of get().
impl block both need a type parameter <T>. Use an associated function new and a method that returns a reference to the field.// Task 2: Generic Wrapper. See tasks/TASKS.md.
fn main() {
todo!("Define Wrapper<T>, new, get, use with \"hello\"");
}
Implement fn largest<T: PartialOrd + Copy>(items: &[T]) -> T that returns the largest element (assume the slice is non-empty). This task is graded by hidden tests that call it with integers *and* chars, so it must be truly generic — a version hard-coded to i32 won't pass.
T: PartialOrd + Copy is what lets you compare with > and copy values out of the slice.// Task 3: implement largest, graded by HIDDEN tests (called with ints AND chars).
// See tasks/TASKS.md.
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
todo!("return the largest item; assume items is non-empty");
}
fn main() {
println!("largest = {}", largest(&[3, 7, 2, 9, 1]));
}