Suppose I have some tuple on the stack:
let a:(u8,u8,u8) = (1,2,3);
How do I create a slice into all, or some of a?
Rust reference defines tuples as having contiguous layout and defined order, so you can take a pointer to the first element of a tuple and transform it to a slice:
#![feature(tuple_indexing)]
use std::slice;
fn main() {
let t = (1u8, 2u8, 3u8);
let f: *const u8 = &t.0;
let s = unsafe { slice::from_raw_buf(&f, 3) };
println!("{}", s); // [1, 2, 3]
}
There is also this RFC but it was closed quite some time ago.
In most cases it doesn't make sense to do this. The main distinction between a tuple and a fixed size array of the same size is that the tuple supports heterogeneous elements, while arrays contain elements of the same type. Slices are fat pointers to an array of values of the ~same type that are consecutive in memory, so while they might make sense for ~some tuples, they don't in general, and therefore slice operations are not supported on tuples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With