Skip to content

Commit 574a6bc

Browse files
committed
Add an example for const generics
1 parent 86bcefd commit 574a6bc

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

src/types/generics/index.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,26 @@ r[generics.const]
329329
r[generics.const.intro]
330330
*Const generic parameters* allow items to be generic over constant values.
331331
332+
> [!EXAMPLE]
333+
> ```rust
334+
> struct Grid<const WIDTH: usize, const HEIGHT: usize> {
335+
> data: [[f32; WIDTH]; HEIGHT],
336+
> }
337+
>
338+
> impl<const WIDTH: usize, const HEIGHT: usize> Grid<WIDTH, HEIGHT> {
339+
> fn new() -> Self {
340+
> Grid { data: [[0.0; WIDTH]; HEIGHT] }
341+
> }
342+
>
343+
> fn size(&self) -> usize {
344+
> WIDTH * HEIGHT
345+
> }
346+
> }
347+
>
348+
> let grid: Grid<4, 4> = Grid::new();
349+
> assert_eq!(grid.size(), 16);
350+
> ```
351+
332352
r[generics.const.namespace]
333353
The const identifier introduces a name in the [value namespace] for the constant parameter, and all instances of the item must be instantiated with a value of the given type.
334354

0 commit comments

Comments
 (0)