4

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.

7
  • 2
    "This... is not a difficult task", difficulty for a compiler is not always obvious. Commented Dec 9, 2019 at 20:56
  • 3
    [0..N] creates an array containing a range; you probably just want 0..N. You can also avoid the closure. The duplicates applied to your example Commented Dec 9, 2019 at 21:41
  • 1
    It isn't difficult, if you use a vector: let 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. Commented Dec 9, 2019 at 21:43
  • @Shepmaster that snippet fails when N > 32. Commented Jan 10, 2020 at 9:46
  • @Stargateur I'm not a compiler expert, but literally no other lang I've ever used has this problem. It's a constant size array. Maybe the devs are running before they can walk... Commented Jan 10, 2020 at 9:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.