Code Logo

Generic Pair Struct

Published at25 Jul 2026
Rust Traits & Generics Medium 2 views
Like0

Write a Rust function that defines a generic struct Pair with two fields of type T. Implement a method sum(self) -> T that adds the two values, but only when T implements the std::ops::Add trait. The function creates a Pair and returns the sum of its two values.

Generic structs in Rust allow defining data structures that work with any type. The syntax Pair introduces a type parameter T which is used for the field types. Methods on generic structs can additionally constrain T with trait bounds using where clauses or inline bounds: impl> Pair { fn sum(self) -> T { ... } }.

The Add trait requires specifying the output type via the associated type Output. By bounding T with Add, we ensure that adding two T values produces another T. This associated type mechanism allows traits to be flexible while maintaining type safety at compile time.

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

Example 1
Input
(100,200)
Output
300
Explanation

100+200=300

Example 2
Input
(5,5)
Output
10
Explanation

5+5=10

Example 3
Input
(1,2)
Output
3
Explanation

Pair of i32 values: 1+2=3

Example 4
Input
(0,0)
Output
0
Explanation

Zero pair

Example 5
Input
(10,20)
Output
30
Explanation

10+20=30

Algorithm Flow

Recommendation Algorithm Flow for Generic Pair Struct
Recommendation Algorithm Flow for Generic Pair Struct

Solution Approach

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()
}

Best Answers

rust - Approach 1
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()
}