Function with Trait Bound
Write a generic Rust function with a trait bound that takes any value implementing the std::fmt::Debug trait and returns the value doubled. The function prints the value using Debug formatting (via {:?}) then returns the doubled value. Demonstrate it works with i32.
Trait bounds in function signatures are specified with the syntax fn func
Using trait bounds, functions can accept any type that has the required capabilities without knowing the concrete type at definition time. This is the foundation of Rust's generics system and enables writing reusable code that works across many types while maintaining full type safety at compile time.
Time complexity is O(1) for the operation itself, plus O(n) for the Debug formatting where n is the string representation length. Space complexity is O(1). The function is monomorphized for each concrete type with zero runtime abstraction overhead.
Edge cases include primitive types that implement Debug (i32, f64, bool, etc.), ensuring the trait bound is specified correctly in the function signature, and understanding that the where clause syntax is an alternative to inline bounds.
Example Input & Output
Normal value
Negative doubled
i32 doubled with Debug: prints then doubles
Zero doubled is zero
Another i32 value
Algorithm Flow

Solution Approach
Best Answers
use std::fmt::Debug;
fn solution<T: Debug>(x: T) -> T {
println!("{:?}", x);
x
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
