T: repr(C) + Copy // fast save/load Vec<T>

  1. We have a struct T that has repr(C) and Copy.

  2. From just the above, can we derive Vec<T> -> file and file -> Vec<T> functions?

  3. If not, what else do we need?

You could use slice::from_raw_parts(_mut) to cast Vec's contents to [u8] for purpose of I/O. Note that you can't cast from [u8] to [T], because it doesn't guarantee alignment.

However, Copy and repr(C) is still not enough to have safe and reliable file representation for any type, because pointers can be Copy and exact size and layout of repr(C) still varies between architectures.

The safe and reliable alternative is bincode.

2 Likes

Thanks, bincode works great!