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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 2
    "This... is not a difficult task", difficulty for a compiler is not always obvious. – Stargateur Dec 09 '19 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](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c655157e8ab0540b00c77e1fda8dbaf2) – Shepmaster Dec 09 '19 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](https://internals.rust-lang.org/t/collecting-iterators-into-arrays/10330/6) also contains some relevant discussion. – trent Dec 09 '19 at 21:43
  • @Shepmaster that snippet fails when N > 32. – whatever923enkj Jan 10 '20 at 09: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... – whatever923enkj Jan 10 '20 at 09:48
  • @whatever923enkj yep, because Rust [hasn't stabilized constant generics](https://stackoverflow.com/q/28136739/155423) yet. The arrayvec crate has feature flags for `array-sizes-33-128` and `array-sizes-129-255` if that happens to cover your cases. Otherwise you have to use one of the other linked solutions. – Shepmaster Jan 10 '20 at 15:04
  • *literally no other lang I've ever used has this problem* — I'd be willing to wager that no other language you've used tries to prevent memory unsafety without overhead, as Rust does. Arrays must always be fully initialized in Rust. – Shepmaster Jan 10 '20 at 15:06

0 Answers0