#Is it a bad idea to put a reference to a parent object in a child function?

11 messages · Page 1 of 1 (latest)

dreamy cedar
#

?eval

struct Child;

impl Child {
  pub fn do_something(&mut self, parent: &mut Parent) {}
}
struct Parent {
  pub child: Child,
}```
outer sluiceBOT
#
()
dreamy cedar
#

Is it a bad idea to put a reference to a parent object in a child function?

#

Should I avoid doing this?

#

From a design perspective.

tepid trellis
#

How would you even call this function?

dreamy cedar
#

Right now I'm passing the specific things from the parent I need the child to mutate

#

?eval

struct Child;

impl Child {
  pub fn do_something(&mut self, parent: &mut Parent) {}
}
struct Parent {
  pub child: Child,
}

fn main () {
  let mut parent = Parent {
    child: Child {}
  };
  
  parent.child.do_something(&mut parent);
}
outer sluiceBOT
#
warning: unused variable: `parent`
 --> src/main.rs:4:34
  |
4 |   pub fn do_something(&mut self, parent: &mut Parent) {}
  |                                  ^^^^^^ help: if this is intentional, prefix it with an underscore: `_parent`
  |
  = note: `#[warn(unused_variables)]` on by default

error[E0499]: cannot borrow `parent.child` as mutable more than once at a time
  --> src/main.rs:15:3
   |
15 |   parent.child.do_something(&mut parent);
   |   ^^^^^^^^^^^^^------------^-----------^
   |   |            |            |
   |   |            |            first mutable borrow occurs here
   |   |            first borrow later used by call
   |   second mutable borrow occurs here

error[E0499]: cannot borrow `parent` as mutable more than once at a time
  --> src/main.rs:15:29
   |
15 |   parent.child.do_something(&mut parent);
   |   --------------------------^^^^^^^^^^^-
   |   |            |            |
   |   |            |            second mutable borrow occurs here
   |   |            first borrow later used by call
   |   first mutable borrow occurs here

For more information about this error, try `rustc --explain E0499`.
dreamy cedar
#

Oh, straight up can't

#

Ok, so passing the values you need down to a child element to mutate is the way to go