Rust
[T; N]
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 8
Matrices, fixed-size buffers, network protocol frames and cryptography blocks are typical uses.
Exercise 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.
Show example 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());
}
Test yourself
-
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
- With a single implementation
Show answer
With macros, separately for each length from 0 to 32 — That's why in old Rust an array of 33 elements couldn't print with Debug; const generics removed that limit.
-
Value parameter
fn toplam<____>(a: [i32; N]) -> i32 {
a.iter().sum()
}
Show answer
fn toplam<const N: usize>(a: [i32; N]) -> i32 {
a.iter().sum()
}
-
Call and N
- toplam([1, 2, 3])
- N = 3
- toplam([10; 4])
- N = 4
- Tampon::<8>::new()
- N = 8
- toplam([])
- N = 0
Next lesson: const fn