Sorry if this is a stupid question, but I'm struggling with what I think is ownership in rust.
I'm completely new to rust, but have done low level languages before so I know the concept of pointers pretty well. However, this rust ownership I can't quite wrap my head around.
I'm trying to refactor my solution to AoC Day 4 Part 2 using a struct reference instead of a stand-alone vector.
The error I'm getting, and can't figure out is in the process function at line
cards.iter_mut().for_each(|card | {
The error is
cannot borrow cards as mutable more than once at a time second mutable borrow occurs here
There is a lot of parsing in my code, so I stuck that in a spoiler below.
The relevant code is:
#[derive(Debug)]
struct Card {
id: u32,
score: u32,
copies: u32,
}
fn process(input: &str) -> u32 {
let mut cards: Vec = parse_cards(input);
cards.iter_mut().for_each(|card| {
let copy_from = card.id as usize + 1;
let copy_to: usize = copy_from + card.score as usize - 1;
if card.score == 0 || copy_from > cards.len() {
return;
}
for card_copy in cards[copy_from - 1..copy_to].iter() {
let id = card_copy.id as usize - 1;
let add = cards[card.id as usize - 1].copies;
cards[id].copies += add;
}
});
return cards.iter().map(|c| c.copies).sum();
}
The error says I can't combine immutable and mutable in the same function. I guess this makes sense, and that it's because I'm not allowed to mutate an object while accessing it.
Is this a correct understanding of the error, or is there anything I can do to use this approach?