Struct creating from another instance

The book under the section “Creating Instances from Other Instances with Struct Update Syntax” describes struct update syntax with the following example.

let user2 = User {
email: String::from(""),
username: String::from("anotherusername567"),

Using struct update syntax to set new email and username values for a User instance but use the rest of the values from the fields of the instance in the user1 variable

Question: Does the compiler generate the field-by-field copying code? As someone who dealt with type versioning in .net I am intrigued by this feature. The owner of the User struct can update the type (add new field). This change will be done independent of the code that is using as above example. If so would the newly added field will not be copied, right?

The newly added field will be copied. The desugaring is something like

let user2 = User {
    email: String::from("..."),
    username: String::from("..."),
    another_field_1: user1.another_field_1,
    another_field_2: user1.another_field_2,
    another_field_3: user1.another_field_3,

When the struct is updated, that's just more copies for the desugaring to generate.

Thanks, quinedot. It is interesting. What I was getting at was how such rust shortcuts fare in the real world of dynamic linking and type evolution.

When a type in a dependency changes, the code has to get recompiled. Dynamic linking is not going to work if you link against a different version of the code than what it was compiled with.

1 Like

Rust's ABI is not stable. There have been some threads on dynamic linking in this forum and on IRLO (and elsewhere I'm sure) that you could search for to read more.

You could get at least partway there in terms of struct layout by using #[non_exhaustive] and #[repr(C)].

I want to thank both of you. I really love the language and the community. I will definitely follow up on Rust's ABI.

While I agree getting a stable ABI is a huge challenge, I was intrigued by the language shortcuts that make the discovering versioning issues harder. For example, it is almost impossible to detect that one of the new properties is not copied by just looking at the code that uses the shortcut.

Yeah, that's true and an interesting observation. I think it just hasn't been a concern in the language design. If dynamic linking becomes more popular or in-demand, I imagine a number of lints would appear around it. I guess the closest thing currently are SemVer guidelines.

I'm interested to see if such pressure does arise and where Rust goes with it, but if anything changes I feel it's quite a ways off. If you want something like it in the mean time, you basically build a C interface. You definitely have to design for it specifically.

1 Like

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.