I have a boxed slice Box<[i32]>
, and would like to allocate it in a way similar to Box::from([0; n])
where n
is a non-const number.
Is there a way to do this without using vectors as an intermediary?
I have a boxed slice Box<[i32]>
, and would like to allocate it in a way similar to Box::from([0; n])
where n
is a non-const number.
Is there a way to do this without using vectors as an intermediary?
You can use .collect()
, e.g.
let x: Box<[i32]> = (0..n).collect();
but generally there's nothing wrong with Vec
. If you use vec.reserve_exact(n)
the conversion should be zero cost.
I guess Box<[T]>
can't grow or shrink like a Vec<T>
, which might be a useful constraint depending on the use case
Given an &mut Box<[T]>
, you can always assign a new Box<[T]>
of a different length to it. So, choosing Box<[T]>
doesn't actually give you any guarantees about the length; it only makes it more inconvenient and inefficient to change the length. Still potentially useful as a hint, but don't write code that relies on it.
Perhaps worth mentioning, Box<[T]>
only needs to store the length
rather than both the length
and capacity
. As such the memory layout is smaller which can be beneficial, and an easy win in cases where you don't actually ever grow the vector.
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.