In C++ there is a member pointer which is actually an offset from the beginning of the structure (along with type of course).
To dereference it, you must provide pointer to struct.
This is much like we store offset for the string.
Most people would just use a closure if they need a way to dynamically access one field or another based between a condition.
struct User {
name: String,
last_name: String,
}
fn main() {
let name_goes_first = false;
let first = |u: &User| if name_goes_first { &u.name } else { &u.last_name };
...
}
Otherwise you could just store the condition in the User struct.
struct User {
name: String,
last_name: String,
name_goes_first: bool,
}
Member references are one of those obscure C++ features that you only really need to reach for in tricky situations, and I don't believe I've seen anything similar in any other language. Technically, it's quite possible to implement the equivalent in Rust as a library because there are ways to calculate offsets of a member and wrap all the unsafety up in a nice API, but I feel like it's got limited value.
To add to this, member pointers are “necessary” in C++ in order to support features like virtual inheritance. It might just be an offset, but it also might involve a vtable lookup. Thus the equivalent in Rust would actually be closer to fn(&User) -> &String.
There's no direct support for this, but if you really do have a reason to need to select between fields, the best way would be with an enum which you implement a method to project the primary reference with. But like any getter, be aware that means borrowing the whole structure.