Generic struct
- Rust course
- Intermediate
- Lesson 8/115
- 4 min
Define and use generic structs.
Generic structs
Struct fields can be generic too. A single type parameter makes all fields the same type; two parameters allow them to differ:
struct Cift<T> {
a: T,
b: T,
}
struct Nokta<T, U> {
x: T,
y: U,
}
let p = Cift { a: 3, b: 7 }; // Cift<i32>
let q = Nokta { x: 5, y: 2.5 }; // Nokta<i32, f64>Vec<T>, Option<T> and HashMap<K, V> are generic types in the standard library.
When to go generic?
Making a struct generic is for cases where the same logic is reused with different contents: container types (stacks, queues, caches), pairs, wrappers. If it will only be used with one type, writing the concrete type is more readable.
struct Kutu<T> {
icerik: T,
}
let sayi = Kutu { icerik: 42 };
let metin = Kutu { icerik: "rust" };
println!("{} {}", sayi.icerik, metin.icerik); // 42 rustPractice Pairs
Define struct Cift<T> { a: T, b: T }. Create p = Cift { a: 3, b: 7 } and q = Cift { a: "x", b: "y" }; print p.a + p.b and q.b separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
struct Cift<T> {
a: T,
b: T,
}
fn main() {
let p = Cift { a: 3, b: 7 };
let q = Cift { a: "x", b: "y" };
println!("{} {}", p.a + p.b, q.b);
}Expected output
10 y
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why doesn't <code>Cift { a: 3, b: 2.5 }</code> compile?
- a and b must be the same type T; i32 and f64 differ Correct answer
- Cift isn't generic
- Floats can't be used
- It compiles
Explanation: Different types need two type parameters, like Nokta<T, U>.
2 Two types
struct Nokta____ {
x: T,
y: U,
}
struct Nokta<T, U> {
x: T,
y: U,
}
Explanation: Two type parameters are declared for fields of different types.
3 Expression and type
| Term | Meaning |
|---|---|
Cift { a: 3, b: 7 } |
Cift<i32> |
Cift { a: "x", b: "y" } |
Cift<&str> |
Nokta { x: 5, y: 2.5 } |
Nokta<i32, f64> |
Kutu { icerik: true } |
Kutu<bool> |