Summary - Const generics
- Rust course
- Advanced
- Lesson 71/81
- 5 min
Combine const fn and [T; N] to build a generic dot product.
Const generics summary
Const generics parameterize types by values: struct S<const N: usize>, fn f<const N: usize>. The size is part of the type; a mismatch is a compile error and no heap is needed. const fn computes at compile time. In stable Rust parameters are limited to integers/bool/char, and expressions like N + 1 can't be used in types. Use try_into for slice ↔ array, and chunks_exact for fixed pieces.
A sized matrix
A matrix carrying its dimensions in the type with two const parameters:
struct Matris<const R: usize, const C: usize>([[i32; C]; R]);
impl<const R: usize, const C: usize> Matris<R, C> {
fn devrik(&self) -> Matris<C, R> {
let mut t = [[0; R]; C];
for i in 0..R {
for j in 0..C {
t[j][i] = self.0[i][j];
}
}
Matris(t)
}
}Multiplication is checked in the signature too: fn carp<const K: usize>(&self, o: &Matris<C, K>) -> Matris<R, K>.
Practice Matrix transpose
Write the Matris<const R: usize, const C: usize> type above and the devrik method. Print the inner array of the transpose of Matris([[1, 2, 3], [4, 5, 6]]) with {:?}.
Starter code
fn main() {
// buraya yaz
}Sample solution
struct Matris<const R: usize, const C: usize>([[i32; C]; R]);
impl<const R: usize, const C: usize> Matris<R, C> {
fn devrik(&self) -> Matris<C, R> {
let mut t = [[0; R]; C];
for i in 0..R {
for j in 0..C {
t[j][i] = self.0[i][j];
}
}
Matris(t)
}
}
fn main() {
let m = Matris([[1, 2, 3], [4, 5, 6]]);
println!("{:?}", m.devrik().0);
}Expected output
[[1, 4], [2, 5], [3, 6]]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the type of the transpose of a <code>Matris<2, 3></code>?
- Vec<Vec<i32>>
- Matris<3, 2> Correct answer
- Matris<2, 3>
- Matris<6>
Explanation: Rows and columns swap; the type system expresses this in the signature: fn devrik(&self) -> Matris<C, R>.
2 Transpose type
fn devrik(&self) -> Matris____ {
..
}
fn devrik(&self) -> Matris<C, R> {
..
}
Explanation: The transpose swaps the row and column counts.
3 Group summary
| Term | Meaning |
|---|---|
<const N: usize> |
Value parameter |
const fn |
Compile-time computation |
try_into |
Slice → array |
Matris<R, C> |
Sized type |