What is the right way to think in rust about &mut

If I have this:

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Balance {
    #[serde(default)]
    pub amount: f64,
    #[serde(default)]
    pub currency: Currency,
}
    struct MyLifeTime<'a> {
        part: &'a mut Balance,
        balance: Balance,
    }
    impl<'a> MyLifeTime<'a> {
        pub fn add_balance(&mut self, num: f64) {
            self.part.amount = num;
            self.balance.amount = num;
        }
    }

This runable:

     #[test]
    fn test_lft() {
        let mut b = Balance {
            amount: 1.1,
            currency: Currency::SANDBOX,
        };
        let m = MyLifeTime {
            balance: b.clone(),
            part: &mut b,
        };
    }

But this doesn't:

     #[test]
    fn test_lft() {
        let mut b = Balance {
            amount: 1.1,
            currency: Currency::SANDBOX,
        };
        let m = MyLifeTime {
            part: &mut b,
            balance: b.clone(),
        };
    }
    |
265 |           let m = MyLifeTime {
    |  _________________-
266 | |             part: &mut b,
    | |                   ------ mutable borrow occurs here
267 | |             balance: b.clone(),
    | |                      ^ immutable borrow occurs here
268 | |         };
    | |_________- mutable borrow later used here

The only difference is the two fields code before or after.
Why? I think the balance filed is clone(), but why said borrow occurs?

Quoting https://doc.rust-lang.org/std/clone/trait.Clone.html:

pub trait Clone {
    fn clone(&self) -> Self;

in the first example:

  1. we need a &self
  2. we use the &self
  3. when we hit the &mut b, we no longer need the &self

in the second example:

  1. we hold on to a &mut b
  2. when we execute the clone, we need a &b -> Self
  3. but we are not allowed to have an immutable ref when there is already a mutable one
2 Likes

Thank you!

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.