How to declare arrays gracefully [Vec<String>;8]

This will report an error.

This is how I deal with it.

    let mut array = [vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![]];

But I think it's ugly.Who can write it better?

use from_fn in std::array - Rust

1 Like

As @zirconium-n said, the general solution is using from_fn.

An alternative that works on older compiler is to use a const:

const EMPTY_VEC: Vec<String> = Vec::new();
let mut array = [EMPTY_VEC; 8];

The downside of this approach is that it works only for values you can const initialize, however it also guarantees you won't do work at runtime for it.


Fine, thank you

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.