Change value in found item

Viewed 87

I'm trying to find and change a specific item in an iterator like this:

struct ItemType {
    name: &'static str,
    value: i32
}

struct OuterType {
    list: Vec<ItemType>
}

impl OuterType {
    pub fn setByName(
        self: &mut Self,
        name: &str
    ) -> Result<(), String> {

        match self.list.iter().find(|item| item.name == name) {
            Some(item_found) => {
                item_found.value = 1;
            },
            None => {
                return Err(format!("unrecognized item name (was \"{}\")", name));
            }
        }

        Ok(())
    }
}

But this does not compile because of several reasons, some of which:

  • no Copy trait (don't want to change a copy, I want to change the item in-place);
  • not borrowed, add & (does not help);
  • not mutable, add mut (does not help);
  • cannot assign to item_found.value which is behind a &;
  • at some point it says & can PROBABLY be removed... (WHAT?);
  • those errors are cyclic, I'm ping-pong-ing between them with no exit.

I've also tried to .find(|&item| ...).

What is going on? Don't I get to own the value returned by find()? And how am I supposed to change item_found.value? It's just an integer in a struct which is one of several in a vector I get the iterator for.

1 Answers

Just use iter_mut instead of iter when you need to mutate the value:

match self.list.iter_mut().find(...) {...}

Playground

Related