2

I need to have a lot of data stored as an immutable variable that can be accessed by every function.

The optimal way would be to use a const DATA: [u64; 1000] = [ 1, 110101, ... ] and that is possible because I know how this data looks like. Due to the huge amount of data that needs to be created, the only practical way is to initialize the constant with a function. That does not currently work in Rust, and it maybe will never, because I need to run loops in the initializer function which isn't even supported in the nightly build.

It should be possible to initialize the data in the main function as ordinary let DATA: [u64; 1000] = ini_fn();. Then I would need to give all subfunctions a reference to this data. That's kinda inconvenient; if a function foo3() were to need the DATA but gets called by foo2() which gets called by foo1() which gets called by main(), I would need to borrow the DATA three times and really using it just once.

I am searching a more reasonable solution for this problem / some equivalent to this C code:

std::array<int, 64>  ini_data()
{
  std::array<int, 64> ret;
  for(int i = 0; i < 64; i++)
  {
    ret[i] = i;
  }
  return ret;
}

const std::array<int, 64> DATA = ini_data();

void main()
{
  print(DATA);
}

It would be better to have this data on the stack because speed is important, but I hope that the data gets cached so this is not a priority.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Darius Duesentrieb
  • 837
  • 10
  • 20
  • 3
    Just remove the "mutable" part of the linked duplicates: `lazy_static! { static ref DATA: Vec = create_data_fn(); }`. – Shepmaster Nov 29 '17 at 22:57
  • 1
    FWIW, I think that actually creating the value in `main` and passing down references is a very reasonable solution. Rust's lifetimes prevent you from shooting yourself in the foot and you can optionally avoid all multithreaded synchronization issues. – Shepmaster Nov 29 '17 at 23:01
  • Actually, i have maybe 10 different arrays that are like the `DATA`-array. Isn't this a performance issue if I call these function (`foo()1, foo()2, foo()3`) very often because I always have to copy the reference-pointer? – Darius Duesentrieb Nov 29 '17 at 23:37
  • 1
    You could also generate the constant by running a function in a build script and then importing the generated code (the 3rd duplicate I added). – Shepmaster Nov 29 '17 at 23:38
  • Accessing the `DATA` variables requires an atomic variable check (to ensure that they have been initialized) and then you get a reference to (in this case) the `Vec` which can be dereferenced to get to the data. I don't believe either of those are really that much overhead, but you can "cache" that by doing something like `let data = &**DATA`, which will set `data` to an `&[u8]` and then pass that down to the pieces you need. – Shepmaster Nov 29 '17 at 23:42

0 Answers0