Const generics

From Rust Community Wiki
Revision as of 00:33, 4 March 2021 by Aloso (talk | contribs) (Note about min_const_generics)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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]

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]