Is it possible to get a struct as a slice - or maybe a slice as a struct?
In other words given something like:
struct Color {
r: f64,
g: f64,
b: f64,
a: f64
}
It would be really nice to be able to get a &[f64] from that for free, without allocating a new one each time - i.e. just to view it as a contiguous block of memory.
Alternatively, I guess one could just keep a private backing vector or array, and setup accessors so that they're gotten via calling color.r() etc...
But for now I'm wondering if there's something built-in to allow this for free
You must add #[repr(C)]. Without this the compiler is free to store fields in any layout/order it wants.
std::slice_from_raw_parts(&color as *const Color as *const f64, 4). It needs to infer proper lifetimes. The easiest way is to put it in a function that takes and returns a reference.
You were faster Anyway, I'll leave it here: Rust Playground (note that here lifetimes are not a problem, since all the program fits in main; in real cases this must be thought of).
BTW: It's best to avoid transmute. It's very easy to do something very wrong with it if you don't specify types explicitly transmute::<from, to>(). For pointer types the as operator works fine.