2

Suppose I have the following two structs:

struct Parent {
    name: String,
}
impl Parent {
    fn create_child(&self) -> Child {
        Child { parent_name: &self.name }
    }
}

struct Child<'a> {
    parent_name: &'a str,
}

Now I'm attempting to create the following struct:

struct Everyone<'a> {
    p: Parent,
    c: Child<'a>,
}

However, the borrow checker won't allow me to do this:

fn main() {
    let p = Parent { name: "foo".to_owned() };
    let c = p.create_child();
    let e = Everyone { p, c }; // error: p already borrowed!
}

How to properly write Everyone struct?

rodrigocfd
  • 6,450
  • 6
  • 34
  • 68
  • 1
    You don't. That's the answer. – Chayim Friedman May 14 '23 at 14:27
  • 1
    Maybe a little more words: Rust is very strict on aliasing. Programming in Rust requires you to rethink some programming paradigms; many known solutions that work in other programming languages are not compatible with Rust. It's still worth it, though, because it usually leads to cleaner and better solutions in the end. – Finomnis May 14 '23 at 19:02

0 Answers0