Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rust, how do you create a slice that is backed by a tuple?

Tags:

slice

tuples

rust

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?

like image 287
Andrew Wagner Avatar asked Jan 10 '23 08:01

Andrew Wagner


2 Answers

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.

like image 157
Vladimir Matveev Avatar answered Jan 12 '23 00:01

Vladimir Matveev


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.

like image 39
Andrew Wagner Avatar answered Jan 12 '23 01:01

Andrew Wagner