Search code examples
rustmacrosrust-macros

Create sum of ones till N using macro in Rust


I would like to create a macro for transforming count!(5) into 1+1+1+1+1. The final reason is to use count!(N) - 1 into a structure definition where N is a const generics.

macro_rules! count {
    (1) => {0};
    (2) => { 1 + count!(1)};
    ($n: tt) => { 1 + count!($n - 1)};
}

struct WindowIterator<I, Item, const N: usize> {
    iter: I,
    values: Box<[Item; count!(N) - 1 ]>,
    index: usize,
}

With this definition, I receive an error like no rules expected the token N .

How can I change my code for making it correct?


Solution

  • Sadly, it's not possible with current stable Rust. Current Rust support for const generics is MVP, and const generics with complex expressions are not supported in stable build.

    However, it's possible with Rust nightly build.

    #![feature(generic_const_exprs)]
    
    struct WindowIterator<I, Item, const N: usize>
    where
        [Item; N - 1]: Sized,
    {
        iter: I,
        values: Box<[Item; N - 1]>,
        index: usize,
    }
    

    Rust Playground link of the example above

    You can check out further details in this official Rust blog post about const generics.