I don't think there is anything to fix. I also don't think it's a particularly common issue. But anyway, there are several ways to do it shorter, depending on the amount of boilerplate you're willing to write and on your use case.
let s: [Arr; 4] = [
(v0, "zero"),
(v1, "one"),
(v2, "two"),
(v3, "three"),
].map(|(v, s)| Arr { v, s });
This is the simplest way to construct an array of structs. Unfortunately, it cannot currently be used to create a const
, because the map
method on arrays isn't const (and due to implementation details, likely won't be const for a long time).
macro_rules! arr {
($({ $v: expr, $s: expr }),* $(,)?) => {
[
$(Arr { v: $v, s: $s }),*
]
};
}
const s: [Arr; 4] = arr![
{ v0, "zero" },
{ v1, "one" },
{ v2, "two" },
{ v3, "three" },
];
The macro-based approach works in any context, and you can use whatever syntax you like. Defining the macro is slightly verbose, though. Depending on how common such arrays are in your code, this could be the best approach. You could also write a more complex macro, which could handle arbitrary structs (personally I consider it an overkill).