Struct as slice?

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

Seems that this won’t be possible without unsafe. You’re essentially requesting some kind of the “reinterpret_cast”, which is unsafe by design.


Oh interesting… I am curious how it would look with unsafe too :slight_smile:

  1. You must add #[repr(C)]. Without this the compiler is free to store fields in any layout/order it wants.
  2. 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.

Also, it already exists for RGBA:

type Color = rgb::RGBA<f64>;

let c = Color::new(0.,0.,0.,1.);
let s = c.as_slice();

You were faster :slight_smile: Anyway, I’ll leave it here: (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.

Thanks, I’ve tried to do this before, but missed the fact that I should do double cast. Updated link in the previous reply.

1 Like

Neat! Do you have other crates for Point, Area, and similar structs?

For area I’ve got

1 Like