Complete the code to define a generic function that prints any type implementing the Display trait.
use std::fmt::Display; fn print_value<T: [1]>(value: T) { println!("{}", value); } fn main() { print_value(42); print_value("hello"); }
The Display trait allows formatting with {} in println!. The function requires T to implement Display.
Complete the code to implement a trait bound for a generic function that returns the length of any type that implements the Len trait.
trait Len {
fn len(&self) -> usize;
}
fn get_length<T: [1]>(item: T) -> usize {
item.len()
}
struct MyString(String);
impl Len for MyString {
fn len(&self) -> usize {
self.0.len()
}
}
fn main() {
let s = MyString(String::from("hello"));
println!("Length: {}", get_length(s));
}The generic function requires T to implement the Len trait to call len().
Fix the error in the generic function by adding the correct trait bound to allow comparison.
fn largest<T: [1]>(list: &[T]) -> &T { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest } fn main() { let numbers = vec![34, 50, 25, 100, 65]; println!("Largest number is {}", largest(&numbers)); }
The PartialOrd trait allows using the > operator to compare values.
Fill both blanks to define a generic struct with a trait bound and implement a method that uses the trait.
use std::fmt::[1]; struct Wrapper<T: [2]> { value: T, } impl<T: Display> Wrapper<T> { fn show(&self) { println!("Value: {}", self.value); } } fn main() { let w = Wrapper { value: 123 }; w.show(); }
The struct and impl both require the Display trait to print the value.
Fill all three blanks to complete a generic function that returns the longer of two string slices using trait bounds.
fn longest<'a, T: [1] + [2]>(x: &'a T, y: &'a T) -> &'a T { if x.len() > y.len() { x } else { y } } fn main() { let s1 = String::from("hello"); let s2 = String::from("world!"); let result = longest(&s1, &s2); println!("Longest string is: {}", result); }
The function requires T to be convertible to str slices (AsRef<str>) and printable (Display).