How to avoid code duplication in this structure literal and make it shorter?

Hello.

How can I make the following structure literal shorter:

    let s = S {
        abc: 1,
        def: 2,

        a1: FUNCA(some.a1),
        a2: FUNCA(some.a2),
        a3: FUNCA(some.a3),
        a4: FUNCA(some.a4),
        a5: FUNCA(some.a5),
        a6: FUNCA(some.a6),
        a7: FUNCA(some.a7),

        b1: FUNCB(some.b1),
        b2: FUNCB(some.b2),
        b3: FUNCB(some.b3),
        b4: FUNCB(some.b4),
        b5: FUNCB(some.b5),
        b6: FUNCB(some.b6),
        b7: FUNCB(some.b7),
    };

If it were possible, I would create a macros that would expand to a list of "key:value," pairs.
However, as HJVT answered in my previous question, it doesn't work the way I tried it.

Is there any other way to make this structure literal shorter and avoid code duplication?

is this what you are looking for?

1 Like

What you can do is write a macro that expands to the entire expression S { ... }, something like this quick playground sketch. You can improve it to not require the trailing commas that lead to the awkward ,; combination when changing "sections", but that's left as an exercise to the reader :slight_smile:

2 Likes

It looks like your code could be written elegantly with an array:

fn main() {
    let some = S { abc: 9, def: 0, a: [42; 7], b: [100; 7]};

    let s = S {
        abc: 1,
        def: 2,

        a: some.a.map(FUNCA),
        b: some.b.map(FUNCB),
    };
    
    dbg!(s);
}

#[derive(Debug)]
pub struct S {
    abc: u8,
    def: u8,
    a: [u8; 7],
    b: [u8; 7],
}

fn FUNCA(x: u8) -> u8 {
    // replace with real contents
    x + 1
}

fn FUNCB(x: u8) -> u8 {
    // replace with real contents
    x - 1
}

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.