-1

Goal Summary: I want to get rid of this error, and have my code to compile.

error[E0502]: cannot borrow `selected` as immutable because it is also borrowed as mutable
  --> src/main.rs:17:26
   |
16 | for tx in selected.iter_mut() {
   |           -------------------
   |           |
   |           mutable borrow occurs here
   |           mutable borrow later used here
17 |         tx.1.edges.push((selected[0].0.clone(), selected[1].0.clone()));
   |                          ^^^^^^^^ immutable borrow occurs here

error[E0502]: cannot borrow `selected` as immutable because it is also borrowed as mutable
  --> src/main.rs:17:49
   |
16 | for tx in selected.iter_mut() {
   |           -------------------
   |           |
   |           mutable borrow occurs here
   |           mutable borrow later used here
17 |         tx.1.edges.push((selected[0].0.clone(), selected[1].0.clone()));
   |                                                 ^^^^^^^^ immutable borrow occurs here

Minimum Reproducible Code:

use std::time::{Duration};
pub struct Transaction {
    pub sender: String,
    pub receiver: String,
    pub amount: f64,
    pub signature: String, 
    pub status: &'static str,
    pub weight: u32,
    pub timestamp: (String, Duration),
    pub index: u32,
    pub edges: Vec<(String, String)>,}

fn main () {
    let mut selected: Vec<(String, Transaction)> = Vec::new(); 
    // The following vec has 2 items. 
    for tx in selected.iter_mut() {
        tx.1.edges.push((selected[0].0.clone(), selected[1].0.clone()));
        tx.1.status = "confirmed"}}

What I've tried: How do I fix cannot borrow `` as mutable because it is also borrowed as immutable

Cannot borrow as mutable because it is also borrowed as immutable

cannot borrow as mutable, as it is behind a `&` reference

None of them really helped me, because either I'm not smart enough to understand or it just wasn't implementable for me. (I mean this in the case that even though we are getting the same errors, it's caused by different things).

user3840170
  • 26,597
  • 4
  • 30
  • 62

1 Answers1

0

I don't understand what you're trying to do in that loop, but if you just define let edges = (selected[0].0.clone(), selected[1].0.clone()) before the loop (as it's not based on anything you're doing in the loop at all, there's no reason for you to do the borrow inside the loop), it should work.

let mut selected: Vec<(String, Transaction)> = Vec::new();
// Some stuff here, I assume, which populates `selected`
let edges = (selected[0].0.clone(), selected[1].0.clone());
for tx in selected.iter_mut() {
        tx.1.edges.push(edges.clone()); // or borrow?
        tx.1.status = "confirmed"}
}
tobiasvl
  • 570
  • 4
  • 20