Code Logo

Function with Trait Bound

Published at25 Jul 2026
Rust Traits & Generics Easy 0 views
Like0

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(x: T) -> T. This means the function works with any type T that implements TraitName. The Debug trait is one of the most common bounds, used for debugging output with {:?} format. The {:?} formatter requires the Debug trait.

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

Example 1
Input
7
Output
14
Explanation

Normal value

Example 2
Input
-5
Output
-10
Explanation

Negative doubled

Example 3
Input
42
Output
84
Explanation

i32 doubled with Debug: prints then doubles

Example 4
Input
0
Output
0
Explanation

Zero doubled is zero

Example 5
Input
100
Output
200
Explanation

Another i32 value

Algorithm Flow

Recommendation Algorithm Flow for Function with Trait Bound
Recommendation Algorithm Flow for Function with Trait Bound

Solution Approach

use std::fmt::Debug;

fn solution<T: Debug>(x: T) -> T {
    println!("{:?}", x);
    x
}

Best Answers

rust - Approach 1
use std::fmt::Debug;

fn solution<T: Debug>(x: T) -> T {
    println!("{:?}", x);
    x
}