[SOLVED] Multidimensional static array referencing other static


#1

Hello, I’ve been trying to create a static array which contains reference to value in another static array. Even though code below should type-check in my opinion. It does not compile. Looking at MIR problem seems to be with [] operator which generates Len((*(a: &'static [&'static [i8]]))); for boundaries checking.

Questions:

  1. Do I have mistake in my reasoning?
  2. What are alternatives
static a: &[&[i8]] = &[&[1]];

static b: &[&[i8]] = &[a[0]];
fn main() {

}

(Playground)

Errors:

   Compiling playground v0.0.1 (file:///playground)
error[E0394]: cannot refer to other statics by value, use the address-of operator or a constant instead
 --> src/main.rs:8:26
  |
8 | static b: &[&&[i8]] = &[&a[0]];
  |                          ^^^^ referring to another static by value
  |
  = note: use the address-of operator or a constant instead

error[E0394]: cannot refer to other statics by value, use the address-of operator or a constant instead
 --> src/main.rs:8:25
  |
8 | static b: &[&&[i8]] = &[&a[0]];
  |                         ^^^^^ referring to another static by value
  |
  = note: use the address-of operator or a constant instead

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0394`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.


#2

I don’t know exactly, but as alternative you can use an one Dimensional Array and allocate with width * height. Indexing would be then y * width + x.


#4

Well, it should work, but I would rather not sacrifice readability. It is pretty low level solution and rust must have other options that are more abstract.


#5

The other way could be Data like

let array: Vec<Vec<i32>>

as example? You can Slice a Vector. It is only an Idea but not tested by myself. I prefer the one dimensional way.


#6

Thank you for your advice, but I must use static for performance reasons


#7

So I have just found out thath in rust 1.29.0 nightly rules for static have been loosened due to const fn. The code in playground is valid since this version.