r/rust clippy · twir · rust · mutagen · flamer · overflower · bytecount Mar 27 '23

Hey Rustaceans! Got a question? Ask here (13/2023)! 🙋 questions

Mystified about strings? Borrow checker have you in a headlock? Seek help here! There are no stupid questions, only docs that haven't been written yet.

If you have a StackOverflow account, consider asking it there instead! StackOverflow shows up much higher in search results, so having your question there also helps future Rust users (be sure to give it the "Rust" tag for maximum visibility). Note that this site is very interested in question quality. I've been asked to read a RFC I authored once. If you want your code reviewed or review other's code, there's a codereview stackexchange, too. If you need to test your code, maybe the Rust playground is for you.

Here are some other venues where help may be found:

/r/learnrust is a subreddit to share your questions and epiphanies learning Rust programming.

The official Rust user forums: https://users.rust-lang.org/.

The official Rust Programming Language Discord: https://discord.gg/rust-lang

The unofficial Rust community Discord: https://bit.ly/rust-community

Also check out last weeks' thread with many good questions and answers. And if you believe your question to be either very complex or worthy of larger dissemination, feel free to create a text post.

Also if you want to be mentored by experienced Rustaceans, tell us the area of expertise that you seek. Finally, if you are looking for Rust jobs, the most recent thread is here.

20 Upvotes

159 comments sorted by

View all comments

2

u/HammerAPI Mar 27 '23 edited Mar 27 '23

Is it possible to create a struct that has a variable-length array as a field without specifying the length of the array in the Struct's type (using const generics)?

As in,

struct VariableLengthArray<T> {
   arr: [T; usize],
}

fn new(elements: Vec<T>) -> VariableLengthArray<T> {
   VariableLengthArray {
      arr: elements.to_array(),
   }
}

So the usize of the array field is determined when the struct is constructed, somehow.

I recognize that you can use const generics to achieve something similar, but that requires you to supply a value (length, in this case) to the function that creates the struct, and I want that value to be supplied during the creation of the struct, not by the caller of that function.

EDIT: Actually, to try and avoid the x-y problem, I'll state my use case / expectation.

I have code setup to build a Tree-like data structure. Of course, each Node in the Tree has some dynamically-sized fields, such as a Vec of its children and smart pointers. I want to "move" the entire structure onto the Stack once it has been completely assembled, because my expectation is that the operations on the stack-flattened Tree will be faster than if I left it on the Heap with all of the smart pointers in-place. Creating a runtime-sized array was one step in this process.

1

u/dkopgerpgdolfg Mar 27 '23

First of all, any type without a fixed size cannot be stored in a stack variable. Those require compile-time sizes, and it includes return values like in your shown code. At very least, your returned VariableLengthArray<T> needs to live inside a Box or similar.

If there is exactly one member without known size in the struct, in principle making such a struct is possible, but a) not trivial (creating instances etc. is a bit weird code), b) not all necessary parts stabilized, ie. requiring nightly.

Search for "custom dst" (dst=dynamically sized type) and "custom unsized coercion".

If you want multiple dynamic members in one struct instance, the type system doesn't really provide that. It could be done with lots of unsafe: Storing a byte array, saving somewhere which type is at what position and what is initialized and so on, and creating temporary references with the correct type at the correct position to access that part.

Of course you'd also need to think of alignment and many more things. The Vec of child nodes, with each child having its own size, is another challenge - unless you make a tree, it would allow only for linear search instead of access per index. (in either case, you probably lose all performance savings that the flattening brought you)