Why does rust complain about the object inside a Box not being sized? shouldn't be the same as a pointer in C?
What specific error are you getting and what code produced it? You can't create a box with a pre-unsized value; you need to coerce your box into one
I'm trying to a box a byte array Box<[u8]>
box is a means of providing ownership for memory – an
array – of a given type.
[u8] is a slice view of some other array's memory; it doesn't own any memory itself, so can't be
You'll have to do something like the following:
let my_array = [1, 2, 3, 4]; let my_box: Box<[u8]> = Box::new(my_array) as Box<_>; let my_vec = vec![1, 2, 3, 4]; let my_box: Box<[u8]> = Box::new(my_vec) as Box<_>;
An alternative approach to creating a
Box<[u8]> would be to allocate the space you want as a
Vec<u8>, fill it with the required values, then call
Vec::into_boxed_slice(). Usually a vector is sufficient, but converting to a boxed slice makes it fixed length and a slightly smaller pointer (since it does not need to store capacity).
I apologize, @TomP, but I disagree:
The more colloquial "slice" most people refer to is
&[T], which does not own memory in and of itself. The slice that is referred to here is simply
[T], which can be owned and also
A way to put my disagreement is as follows:
&[T]is a view to the memory, a "pointer and a length" description fits this well.
[T]is the memory under
&[T](Or equivalent), and most certainly has a size, it's just unknown until runtime.
Therefore, it can own itself, just like how
dyn Foo technically owns itself, we just need some kind of wrapper to take care of destruction, and placing some pointer to it on the stack, which just so happens to be the
* If by not capitalizing
box on purpose, and are not referring to the type, and instead the operation
box x, then my point is invalid.
box x does not support
T: ?Sized and you cannot cast
dyn Trait directly because that also requires the input and output to be
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.