Hi Rustaceans.
I've always thought about structs as some kind of hashmaps given that they look pretty similar to JS objects (I come from a JS background). Lately I've been studying the memory representation of various data structures and to my surprise, the memory layout of both normal structs and tuple structs are almost the same to that of tuples: each value within the struct is laid out one after the other in stack memory with some alignment and padding. No reference to the field name or field index is stored in memory, only the values of fields are stored. Additionally, the order of the fields in the Rust code is not guaranteed to be the same in memory as the compiler might change it for memory optimization.
What I don't quite understand is how does the Rust compiler perform the access to the fields within those kinds of structs. Let me explain my reasoning:
For arrays the process is straightforward as I know that an access expression is transformed into the address where the array is stored plus the index: an access like foo[3]
means something like "go to the address where foo
starts and add 3 times the size of the array item type and there's the value you're looking for". However, in a tuple struct, an access like foo.3
can't work that way since each value can have a different size and the order of the values is not guaranteed. In a normal struct, an access like foo.myfield
clearly don't have a number, so number indexing does not apply, and given that the field name is not stored in memory, I'm not sure how does the compiler perform the access under the hood.
So my question regarding struct field access is, since only values are stored in the actual memory layout, and the size of each field can be different, and the order in which those values are stored might not be the order specified in the Rust code, then how does the compiler know which part of memory to target when an access to a specific field is made? Does the compiler internally register the final place in memory of each individual field within the struct and when a field is accessed it then knows exactly to what place in memory that access belong?