Spread in struct

IIUC, Rust only allows one one struct to be spread inside another and it must appear at the end.
For example:

let p = Person {
    name: 'Mark',
    ..otherPerson
};

I'm curious what the rationale is for those restrictions. JavaScript allows spreading any number of objects in another one and the order is significant in determining which field values are used. That seems useful.

A given struct always has the same fields because Rust is statically typed. If multiple instances of FRU (Field Record Update) syntax were allowed with "first wins" or "last wins" semantics, then the fields of the first or last occurrence would always override the others, hence allowing multiple occurrences would be useless anyway.

6 Likes

[inaccurate description of FRU was here]

Not necessarily complicate, but it would simply be useless. After a single ..other_person there are no fields left uninitialized, so adding additional ..persons would simply be a no-op.

2 Likes

Yes, good point! Not allowing uninitialized fields makes all the difference from JS.

1 Like

not quite accurate. It is more like: in place of ..other_person in the desugared version you'll be writing a bunch of field_name: other_person.field_name, for every remaining field named field_name. This will move some fields out of the original struct if they aren't Copy. The remaining ones would then only be dropped at the end of the scope of other_person. Also for this reason, all the fields, including the ones that aren't written out explicitly are required to be visible (e. g. public). And the struct can't be #[non_exhaustive] except when it's defined in the same crate. And when fields are moved, the struct can't have a Drop implementation.

Compare the relevant section in the reference:

Struct expressions - The Rust Reference

2 Likes

Ah, that makes sense. I wasn't considering that structs cannot have optional fields the way JavaScript objects do.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.