Code Logo

Generic Wrapper Struct

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

Write a Rust function that defines a generic struct Wrapper with a single field of type T, and a method value(self) -> T that returns the inner value. The function creates a Wrapper and returns the value.

Generic structs are defined with angle brackets after the struct name: Wrapper. The type parameter T acts as a placeholder that is replaced with a concrete type when the struct is used. Wrapper creates a version of Wrapper where T is i32. This is called monomorphization and happens at compile time with zero runtime cost.

Rust's generics are similar to templates in C++ but with important differences: they are type-checked at the definition site, support trait bounds for constraining type parameters, and integrate seamlessly with Rust's trait system. Generic structs are the foundation for many standard library types like Option, Result, Vec, and Box.

Time complexity is O(1) as the method simply moves the value out of the struct. Space complexity is O(1). The generic wrapper adds no overhead beyond the size of T itself.

Edge cases include T being a non-Copy type (the move still works), T being a reference type, and ensuring the method consumes self to move ownership of the inner value to the caller.

Example Input & Output

Example 1
Input
-5
Output
-5
Explanation

Negative value

Example 2
Input
0
Output
0
Explanation

Zero

Example 3
Input
42
Output
42
Explanation

Wrapper of i32 returns the value

Example 4
Input
100
Output
100
Explanation

Different i32 value

Example 5
Input
7
Output
7
Explanation

Another value

Algorithm Flow

Recommendation Algorithm Flow for Generic Wrapper Struct
Recommendation Algorithm Flow for Generic Wrapper Struct

Solution Approach

struct Wrapper<T> {
    value: T,
}

impl<T> Wrapper<T> {
    fn value(self) -> T {
        self.value
    }
}

fn solution(x: i32) -> i32 {
    let w = Wrapper { value: x };
    w.value()
}

Best Answers

rust - Approach 1
struct Wrapper<T> {
    value: T,
}

impl<T> Wrapper<T> {
    fn value(self) -> T {
        self.value
    }
}

fn solution(x: i32) -> i32 {
    let w = Wrapper { value: x };
    w.value()
}