C++-style member pointers as solution to self-referential struct?


Coming from C++ I found that pointer to struct member may help resolving the self-referential struct problem. If Rust had similar feature we could write something like this

struct SelfRef {
    val: String,
    ptr: Self::* String // A pointer a String in the struct, represented by the member's address offset from the struct's beginning

impl SelfRef {
    pub const fn new(val: String) -> Self {
        SelfRef {
            ptr: &Self::val // Initiallize `ptr' to the address offset of Self::val
    pub fn get_val(&self) -> &String {
        // dereference `ptr', which looks something like 
        //      &*((self as *const u8).offset(self.ptr) as *const <typeof self.ptr>)
        // Since self.ptr points to something in the struct, borrowing it also borrow self

No unsafe code involved, no need for Pin. There's no aliasing problem too, since ptr is only "half of" a pointer, it doesn't actually point to anything until combined with an object.

Is there any problem with this approach?

Will it have the semantics of the raw pointer? If so, you need the unsafe context to access the value behind it. Will it have the semantics of the references? If so, it can't be moved or mutated while the reference to itself is alive, which is the lifetime of...itself.

1 Like

You can't dereference a member pointer directly since it only contain the address offset value, so it's neither raw pointer or normal reference. No referencing or borrowing occurs when initialize or modifying a member pointer, they only happen when you access a struct member of some object. And accessing members with member pointer should follow the same borrowing rule as direct access to a field.

In this case, you will need to pass the self object explicitly, at which point it's really not adding any value compared to just writing code that doesn't store the pointer to the field, and instead recomputes it every time it's needed.

By the way, this forum is not meant for discussing RFC proposals; for that, the Internals forum should be used.

1 Like

Which is here:

Would you look at that, I've been working on just that with @ckaran. The RFC settled on making this a library, you can aee the latest developments in the generic-field-projection repository.

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.