The most efficient way to create a const array from an array by adding one element

const PARENT: &str = "parent";
const CHILD: [&str; 2] = [PARENT, "child"];
const GRANDCHILD: [&str; CHILD.len() + 1] = [CHILD[0], CHILD[1], "grandchild"];
const GREATGRANDCHILD: [&str; GRANDCHILD.len() + 1] = [GRANDCHILD[0], GRANDCHILD[1], GRANDCHILD[2], "greatgrandchild"];
...

Suppose I have to make from 8th to 16th generation of such kind of consts, can I define each of them not by hand, but by macro?

The effort to write the macro would probably exceed the effort to write the constants by hand. A proc macro could do it.

There are quite a few constructs that already work in const, in particular some forms of mutability. the notable ones that do not, however, are for, array::map, and mutable references themselves. But since you start with a newly-to-add const value that can be your valid initializer before overwriting / copying the other elements.

const A: [&str; 8] = ["Tree"; 8];

const B: [&str; 9] = {
  const T: &str = "newelement";
  let mut v = [T; 9];
  let mut i = 0;
  loop {
    if i >= 8 { break; }
    // This only works becasue array indexing with usize is builtin.
    v[i] = A[i];
    i += 1;
  }
  v
};

That would be straightforward to provide the body here as a macro_rules!, too. Maybe even a good excercise to learn many things about the writing of macros.

2 Likes

Thanks.

macro_rules! vtnode {
    ($variable_name:ident, $parent:expr, $node:expr) => {
        const $variable_name: [&str; $parent.len() + 1] = {
            let mut v = [$node; $parent.len() + 1];
            let mut i = 0;
            loop {
              if i >= $parent.len() { break; }
              // This only works becasue array indexing with usize is builtin.
              v[i] = $parent[i];
              i += 1;
            }
            v
        };
    };
}

const ROOT: [&str; 0] = [];
vtnode!(PARENT, ROOT, "parent");
vtnode!(CHILD, PARENT, "child");
vtnode!(GRANDCHILD, CHILD, "grandchild");
vtnode!(GREATGRANDCHILD, GRANDCHILD, "greatgrandchild");
1 Like

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.