1

Can I initialize an array of structs so that I can use it but without initializing the data at the allocated memory with any default or custom initializer? The reason I want to do this is mainly performance.

I don't care if the memory is just garbage, I can guarantee that whenever I need to access a variable of this array the values will be defined.

Maybe I can split this question into two smaller ones:

  1. How can I initialize a struct instance without changing the data at the allocated memory?
  2. How can I initialize an array without changing the data at the allocated memory?

The code that I would like to write:

struct AbcStruct {
    pub a: i32,
    pub b: i32,
    pub c: i32,
}

fn main() {
    let mut a: [AbcStruct; 128];
    println!("{}", a[3].a);
}

In C++ I would do this:

struct AbcStruct
{
  int a;
  int b;
  int c;
};

int main()
{
  AbcStruct a[128];
  std::cout << a[0].b << std::endl;
  return 0;
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Darius Duesentrieb
  • 837
  • 10
  • 20
  • 1
    *The reason I want to do this is mainly performance* — please benchmark your code before resorting to unsafe. *I can guarantee that whenever I need to access a variable of this array the values will be defined* — your demonstration code doesn't even do this correctly; you read `a[3].a` before defining it. – Shepmaster Dec 22 '17 at 19:30

0 Answers0