I want to make an array of structs in Rust, with each struct initialised to different values, with the logic handled by a constructor. The size of the array is known at compile time but is greater than 32.
struct Foo {
foo: isize,
}
impl Foo {
pub fn new(i: isize) -> Foo {
//do stuff with i
Foo { foo: i }
}
}
fn main() {
//this was my best guess...
let foo_array: [Foo; N] = [0..N].iter().map(|i| Foo::new(i));
}
This seems like I should be a really common task but I've not seen any useful material on this at all; what am I missing? This... is not a difficult task, and the only online material I've seen that comes close is futzing around with unsafe blocks and other things that just shouldn't be necessary for a static-size array.
[0..N]creates an array containing a range; you probably just want0..N. You can also avoid the closure. The duplicates applied to your examplelet foo_vector: Vec<_> = (0..n).map(Foo::new).collect();Perhaps one day we will be able to collect into a fixed-size array, but solving that problem is more complicated than you might think (what should happen if a panic occurs when the array is half initialized?) This internals thread also contains some relevant discussion.