Const generics

From Rust Community Wiki
Jump to navigation Jump to search

Const generics are a nightly-only feature that is still in development. It will allow Rust code to be generic over values, such as numbers or strings.

A subset of const generics, called min_const_generics, has been stabilized and will land in Rust 1.51.

Example[edit | edit source]

This example demonstrates how const generics can be used on nightly:

#![allow(incomplete_features)]
#![feature(const_generics)]

struct Array<T, const N: usize>([T; N]);

impl<T, const N: usize> Array<T, N> {
    fn new(value: T) -> Self
    where
        T: Copy,
    {
        Array([value; N])
    }
}

let arr: Array<i32, 7> = Array::new(0);

See also[edit | edit source]