Array as a struct field

Rust doesn’t have the concept of a variable-length (stack) array, which you seem to be trying to use here.

Rust has a couple different array-ish types.

  • Vec<T> (“vector”): Dynamically sized; dynamically allocated on the heap. This is probably what you want to use. Initialize it with Vec::with_capacity(foo) to avoid overallocation (this creates an empty vector with the given capacity).
  • [T; n] (“array”): Statically sized; lives on the stack. You need to know the size at compile time, so this won’t work for you (unless I’ve misanalysed your situation).
  • [T] (“slice”): Unsized; usually used from &[T]. This is a view into a contiguous set of Ts in memory somewhere. You can get it by taking a reference to an array, or a vector (called “taking a slice of an array/vector”), or even taking a view into a subset of the array/vector. Being unsized, [T] can’t be used directly as a variable (it can be used as a member of an unsized struct), but you can view it from behind a pointer. Pointers referring to [T] are fat ; i.e. they have an extra field for the length. &[T] would be useful if you want to store a reference to an existing array; but I don’t think that’s what you want to do here.

Leave a Comment

404 Not Found

Not Found

The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.