0
votes

I'm trying to create a struct that contains a list of other structs, (could be fixed size if that helped)

struct Container<'m> {
    contained: Vec<&'m Contained>,
}

struct Contained {
    id: u64,
}

impl Container<'_> {

    pub fn new<'m>() -> Container<'m> {
        Container {
            contained: Vec::new()
        }
    }

    pub fn new_contained<'m>(&mut self, id: u64) {
        let c = Contained {
            id
        };
        self.contained.push(&c);
                            ^^ lifetime of Contained ends here
    }
}

I can see that life time of Contained ends but I cant see how to create a struct with a given lifetime.

Do I have any alternatives I tried using a fixed size array instead of a Vec this way the Container owns the contents of the Array, but I cant create a zero sized array to start with.

1
Why does your Vec contain references to Contained? Simply contained: Vec<Contained> should suffice for most use cases.Sebastian Redl
Please explain your requirements. In other words, what are you trying to achieve? Where are your Contained objects? They have to live somewhere else that outlives the Container.Acorn
I specifically dont want Cobntained to outlive Container. I wou8ld like objects with the same life time, and I need to reference with pointers &Contained because otherwise I get size not know during complication errors.teknopaul

1 Answers

0
votes

Answering my own question , it seem Box does what I want

struct Container {
    contained: Box<Option<Contained>>
}

struct Contained {
    id: u64,
}

impl Container {

    pub fn new() -> Container {
        Container {
            contained: Box::new(None),
        }
    }

    pub fn new_contained(&mut self, id: u64) {
        let c= Contained {
            id
        };
        self.contained = Box::new(Some(c));
    }
}

Contained appears to live the same lifetime as Container.