Cloning recursive generic type

Hello,

I want to clone a generic struct by using a recursive function, but I am unable to deal with previous type:

The compiler can't recognize the previous generic type.

Is it possible to rebuild a clone with such a struct ?

Thank you in advance for your help.

You would probably benefit from reading Introduction - Learning Rust With Entirely Too Many Linked Lists , which talks in detail about all the pitfalls of implementing linked lists in Rust. There are a few things I see right away, though:

  • &’a mut Something<‘a> is an antipattern that will cause you lots of headaches, so you’ll want to make this change;

    -    fn push(&’a mut self, data: Data) -> S<'a, Self, Data> {
    +    fn push(&mut self, data: Data) -> S<'_, Self, Data> {
    
  • You can’t clone an &mut in general because it represents exclusive access, and the access isn’t exclusive anymore if there are two copies. You can reborrow it, though, temporarily giving away the exclusive access, which lets you make a shallow clone:

        fn shallow_clone(&mut self) -> S<'_, Previous, Data>
        where
            Data: Clone,
        {
            S {
                previous: self.previous.as_mut().map(|x| &mut **x),
                data: self.data.clone(),
            }
        }
    
  • Without knowing more about your use case, it’s impossible to say for sure, but I suspect that you’d be better served by storing previous: Option<Box<Previous>> instead


Playground with the first two changes

2 Likes

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.