fn main() {
// 1
let empty_arr1: [i32; 0] = [];
// 2
let empty_arr2: [i32; 0];
// 3
let empty_arr3 = [0u8; 0];
}
For what cases does the allocation occur?
- Yes
- No
- Yes
Am I right?
fn main() {
// 1
let empty_arr1: [i32; 0] = [];
// 2
let empty_arr2: [i32; 0];
// 3
let empty_arr3 = [0u8; 0];
}
For what cases does the allocation occur?
Am I right?
None of them allocate. They don't allocate on the heap because arrays are inline values. They don't allocate on the stack either because they're zero-sized.
Thanks) Are there any other ways to create an empty array ?
There's a ton of ways in some sense or another...
// e.g.
let _: [u8; 0] = Vec::new().try_into().unwrap();
...but why?
To demonstrate how to create an empty array. I don’t really know where this will come in handy, but still
Generally that's just []
when the type can be inferred (like #1) or [dummy_value ; 0]
where it can't be inferred but a dummy value is readily available (ala #3).
If neither applied, there are various workarounds that aren't really empty-array specific, like using an annotated temporary or calling a function that returns the value, etc.
All arrays of size 0 implement Default
for example.
let _ = <[SomeType; 0]>::default();
Thanks)
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.