Deferred assignment of a field in a struct

Hello,

Here is the code snip:

I'm trying to assign a child struct, but after the parent was initialised.
I added the previous field which is unnecessary in my case, but it shows the parent is linked as expected by using Self as type: so I get access to the parent fields.

Is it only doable for parent ?

Thank you in advance for your help.

It's just not doable as written.

        let s = S { .. };
        self.next = Some(&mut s);
        s

For one, s can't be moved[1] while there's a reference to it alive -- the reference would dangle. For two, more generally, you can never take a reference to a local like s for a lifetime that exists outside of the function body like 'a -- s must either move or go out of scope by the end of the fundion body.

    fn push(&'a mut self, data: Data) -> ..

You don't want self: &'a mut S<'a, ..> either.

Your link-list-esque chain of arbitrarily typed data is suspect too, but I don't know enough about the high-level goal to say much else.


At a minimum, you have some misconceptions about references. They're generally for short-lived borrows and don't, for example, cause the referent to stay alive. (Rust has no builtin garbage collector to make that feasible.)

Maybe Boxes (which are like an owning pointer) and/or type erasure could help, but that's mostly a shot in the dark. Maybe the design generally is a poor fit for Rust.


  1. or otherwise used, since this is an exclusive reference (&mut) ↩ī¸Ž

1 Like

Ok, but maybe doable using unsafe code :scream: because rust safety is too strict for such a case.

Even with unsafe, &mut aren't the right tool for the job. Creating two &mut to the same place which can be active at the same time is UB. Raw pointers may be a better fit.

Even though it's about homogenous linked lists, you may want to read this book.

3 Likes

I followed your expertise by using Rc and RefCell, but I am stuck at the same point:

I am unable to find the right and full featured type for next as I was able to do for previous.
What is going wrong with the typing ?

Looks like you're trying to change the type of the self.next field dynamically. Rust is statically typed so that's not possible.

If you tried to reconstruct self into a new type as well, you'd just push the problem backwards into previous.

Rust doesn't support infinite types or cyclic types or lazy typing or whatnot. Maybe something is possible with type erasure.

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.