Is there a macro to figure out the array size during compile time?

Hey guys:

const SHAPES: [&'static str; 3] = ["Square", "Triangle", "Line"];

Is there a macro so that I don't have to define the array size so during compile time it will figure out the array size?

You can write one, but it's probably more trouble than it's worth: Rust Playground

macro_rules! declare_array {
    (const $name:ident: [$ty:ty; _] = [$($expr:expr,)*];) => {
        const $name: [$ty; array_size!($($expr,)*)] = [$($expr,)*];
    };
    (const $name:ident: [$ty:ty; _] = [$($expr:expr),*];) => {
        declare_array!{
            const $name: [$ty; _] = [$($expr,)*];
        }
    };
}

macro_rules! array_size {
    () => { 0 };
    ($head:expr, $($tail:expr,)*) => {
        1 + array_size!($($tail,)*)
    };
}
3 Likes

Perhaps this crutch can do. It’s still a crutch though.

1 Like

You can make it a variable-length slice:

const SHAPES: &[&str] = &["Square", "Triangle", "Line"];
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.