Others have made the distinction that a
[u8]
(a Dynamically-sized view into a contiguous sequence [T]
) is ideally referred to as a bare slice. We can make the distinction that a shared slice type is &[T]
and one that is mutable is a &mut [T]
.Slices are basically a ptr and the length of the "view", and therefore have twice size of pointers (when compared to
Sized
types).let pointer_size = std::mem::size_of::<&u8>();
assert_eq!(2 * pointer_size, std::mem::size_of::<&[u8]>());
There's a handy function
core::array::from_fn
which can be used like thisfn main() {
let buf = core::array::from_fn::<u8, 4, _>(|i| (i * 2).try_into().unwrap());
let buf = &buf[buf.len() - 1..buf.len() as usize];
let byte = u8::from_le_bytes(core::array::from_fn::<u8, 1, _>(|_| {
buf.iter()
.copied()
.next()
.expect("Unable to read into shared slice")
}));
dbg!(byte);
}
I've used it twice with a closure to ensure the initialised elements are different without the need to mutate it after the fact. Also notice that we used a
Copy
operation, which is quite nice.My interest in
no_std
continues and working at the byte level without a heap
is interesting, as you have to think differently.Click to try this in the playground.