book icon indicating copy to clipboard operation
book copied to clipboard

Improve description of access to Struct instances when a field is moved

Open tschier opened this issue 9 months ago • 6 comments

Chapter 5.1 has this paragraph:

Note that the struct update syntax uses = like an assignment; this is because it moves the data, just as we saw in the “Variables and Data Interacting with Move” section. In this example, we can no longer use user1 as a whole after creating user2 because the String in the username field of user1 was moved into user2. If we had given user2 new String values for both email and username, and thus only used the active and sign_in_count values from user1, then user1 would still be valid after creating user2. Both active and sign_in_count are types that implement the Copy trait, so the behavior we discussed in the “Stack-Only Data: Copy” section would apply. We can still use user1.email in this example, since its value was not moved out.

As a newcomer, these three portions weren't easily reconcilable:

we can no longer use user1 as a whole

This may be read as "neither user1 itself nor any part of user1 is accessible."

Both active and sign_in_count are types that implement the Copy trait, so the behavior we discussed in the “Stack-Only Data: Copy” section would apply.

That section doesn't describe behaviour in the context of structs (i.e. that those fields are still accessible).

We can still use user1.email in this example, since its value was not moved out.

This seems to contradict the first line above, that the whole over user1 is not able to be used

I propose that the book should explicitly call out that access to user1 and its fields is not straightforward. Direct access to the user1 instance is no longer valid as one or more of its fields have been moved; but that access to any of the fields that have not been moved (because they implement Copy) is still valid.

tschier avatar Jan 21 '25 22:01 tschier