Another argument for `&out` references: safe union usage

currently, it is possible to set a union field from safe code.

theoretically, it would also be safe to read or take a reference to the field that was just assigned. unfortunately, there's no way to do this today with only safe rust code.

if we had &out, we could write code like this:

union Un {
  a: char,
  b: usize,
}

let u = Un{ a: 'a' };
let r = &out u.b;
// presumably there would be a function that can write to `&out T` and return `&T` or `&mut T`

technically, for this usecase, we don't need the linear type behavior of &out T, so we could use &mut MaybeUninit<T>, but we would need a way for safe code to get a MaybeUninit reference to a struct field, which would require either special syntax or macro trickery.

I don't understand your example. You say "we can't write to a union field and then safely read it", but in your example you read and write to entirely different fields. How would out-references help with safely dealing with unions? Seems like you wouldn't gain anything besides what a simple let a: u32; foo(&out a); would give you, so what does it has to do with unions?

This is doable by macros, and I don't think it is needed enough to make it a language feature.

That's exactly what standard library methods like https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.write do, without needing &out.

But you still need to have a way to safely get MaybeUninit from a union field.

1 Like

Seems like something you could do with a derive macro.