Generic Pair Struct
Write a Rust function that defines a generic struct Pair
Generic structs in Rust allow defining data structures that work with any type. The syntax Pair
The Add trait requires specifying the output type via the associated type Output. By bounding T with Add
Time complexity is O(1) as addition is a primitive operation for numeric types. Space complexity is O(1). The generic function is monomorphized for each concrete type, producing specialized machine code with zero runtime overhead.
Edge cases include zero values, negative numbers (for signed types), and ensuring the Add trait bound allows the + operator to be used within the method body.
Example Input & Output
100+200=300
5+5=10
Pair of i32 values: 1+2=3
Zero pair
10+20=30
Algorithm Flow
Solution Approach
Define a generic pair struct that can hold two values of potentially different types using type parameters <T, U>. Generics allow the struct to work with any types while maintaining type safety.
Type parameters are specified in angle brackets. The compiler monomorphizes generic code, creating concrete implementations for each type used, resulting in zero runtime overhead.
Time O(1), Space O(1).
Best Answers
use std::ops::Add;
struct Pair<T> {
first: T,
second: T,
}
impl<T: Add<Output = T>> Pair<T> {
fn sum(self) -> T {
self.first + self.second
}
}
fn solution(a: i32, b: i32) -> i32 {
let p = Pair { first: a, second: b };
p.sum()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
