[T; N]
- Rust course
- Advanced
- Lesson 66/81
- 4 min
Learn generic types with const parameters.
[T; N]
Const generics let you parameterize types and functions by a value. Their most common use is array length: the N in [T; N] can now be generic:
fn toplam<const N: usize>(a: [i32; N]) -> i32 {
a.iter().sum()
}
struct Tampon<const N: usize> {
veri: [u8; N],
}
impl<const N: usize> Tampon<N> {
fn new() -> Self {
Self { veri: [0; N] }
}
}In the call toplam([1, 2, 3]), N = 3 is inferred. A separate copy is compiled for each different N (monomorphization).
The value is part of the type
Tampon<4> and Tampon<8> are different types; one can't be passed where the other is expected. Since the size is known at compile time, no heap allocation is needed and bounds checks are often removed entirely:
let a: Tampon<4> = Tampon::new();
let b = Tampon::<8>::new();
println!("{} {}", a.veri.len(), b.veri.len()); // 4 8Matrices, fixed-size buffers, network protocol frames and cryptography blocks are typical uses.
Practice Fixed-size arrays
Write the toplam function above and the Tampon<const N: usize> type. Print the results of toplam([1, 2, 3]), toplam([10; 4]) and Tampon::<8>::new().veri.len() separated by spaces.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn toplam<const N: usize>(a: [i32; N]) -> i32 {
a.iter().sum()
}
struct Tampon<const N: usize> {
veri: [u8; N],
}
impl<const N: usize> Tampon<N> {
fn new() -> Self {
Self { veri: [0; N] }
}
}
fn main() {
println!("{} {} {}", toplam([1, 2, 3]), toplam([10; 4]), Tampon::<8>::new().veri.len());
}Expected output
6 40 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Before const generics, how were trait implementations for arrays written?
- They couldn't be
- By converting to Vec
- With macros, separately for each length from 0 to 32 Correct answer
- With a single implementation
Explanation: That's why in old Rust an array of 33 elements couldn't print with Debug; const generics removed that limit.
2 Value parameter
fn toplam<____>(a: [i32; N]) -> i32 {
a.iter().sum()
}
fn toplam<const N: usize>(a: [i32; N]) -> i32 {
a.iter().sum()
}
Explanation: A const generic parameter is declared as const NAME: TYPE.
3 Call and N
| Term | Meaning |
|---|---|
toplam([1, 2, 3]) |
N = 3 |
toplam([10; 4]) |
N = 4 |
Tampon::<8>::new() |
N = 8 |
toplam([]) |
N = 0 |