What is the output of this Rust program that uses a generic function to print values?
fn print_value<T: std::fmt::Display>(value: T) {
println!("Value: {}", value);
}
fn main() {
print_value(42);
print_value("hello");
}Look at the trait bound std::fmt::Display and how it allows printing.
The generic function print_value accepts any type T that implements the Display trait. Both 42 (integer) and "hello" (string slice) implement Display, so the function prints them as expected.
Which statement best describes why generic functions in Rust often require trait bounds?
Think about how Rust ensures safety and correctness with generics.
Trait bounds tell the compiler what capabilities a generic type must have, so the function can safely use those operations. Without trait bounds, the compiler cannot guarantee the code will work.
What error does this Rust code produce?
fn add<T>(a: T, b: T) -> T {
a + b
}
fn main() {
let result = add(5, 10);
println!("{}", result);
}Consider what trait is needed to use the + operator in Rust.
The generic type T does not have a trait bound specifying it supports the + operator. Rust requires the Add trait bound to use + on generic types.
Which option shows the correct syntax for a generic function that takes two different types and returns a tuple of them?
Remember how to return a tuple in Rust.
Option A correctly defines a generic function with two type parameters and returns a tuple (a, b). Option A returns the wrong tuple order. Options C and D have syntax errors in the return statement.
What is the output of this Rust program?
fn longest<'a, T>(x: &'a T, y: &'a T) -> &'a T where T: std::fmt::Display + PartialOrd, { if x >= y { println!("{} is longer or equal", x); x } else { println!("{} is longer", y); y } } fn main() { let a = "apple"; let b = "banana"; let result = longest(&a, &b); println!("Longest: {}", result); }
Consider how string slices compare and the trait bounds used.
The function compares two references to types that implement PartialOrd and Display. Since "banana" is lexicographically greater than "apple", it prints "banana is longer" and returns a reference to "banana".