Const 2d array definition

Hello. I'd like to ask if there's way to initialize 2d array with f64 values as const. Something like:

const ARR = [ [1.0, 2.0 ], [ 3.0, 4.0, 5.0 ] ]

Lengths of inner arrays are different. I've tried

  1. Vec<Vec<f64>> - but vectors can't be const as far as I understood
  2. [[f64; ???]; 15] - but I don't know length of inner arrays (it can be different)

Thanks!

By definition, an array has elements all of the same type, and an array's length is part of its type, so the inner lists cannot be arrays. The const-compatible type that doesn't specify a fixed size is a slice reference; you can use an array of slice references.

const ARR: [&[f32]; 2] = [&[1.0, 2.0], &[3.0, 4.0, 5.0]];

Thanks a lot, I'll try this!

Additional question to your response:

How slice reference is stored in memory? I am curious because afaik const requires sized types - so slice ref should be sized, I guess.

Slices are stored as FatPointers, so pointer to memory, then size

Thank you!

Minor nits: a pointer to memory and the number of elements, and the order of them is not guaranteed generally and not guaranteed to be the same across difference slice types.

Can you elaborate on order part? Reordering items in array makes no sense generally because this structure is mostly used to order something.

I wasn't talking about the content of the slices (or arrays), I was talking about the layout of wide pointers. Probably it's nothing you care about and you can ignore me (I was just reacting to the phrasing "then size").


But anyway, given two slice wide pointers &[T] and &[U], Rust does not promise any of

  • Either one is a pointer to data followed by a length
  • Either one is a length followed by a pointer to data

And what I meant by ordering is that one could be a pointer to data followed by a length while the other is a length followed by a pointer to data.

(Instead you use functions like from_raw_parts if you're doing things that care about such low-level details, which I don't think you are.)

Ah okay. Thanks for exaplanation anyway. I am learning Rust and I am glad for any meaningful piece of information like yours :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.