Can only break with a value inside `loop` or breakable block

Hello

I have a function which takes a string as a parameter. This parameter is the name of a cat. Now I want to return the cat from my vector of cats matching that name (assuming that all the cats have unique names).

This is a working solution:

    fn get(&mut self, name : String) -> Option<&Cat> {
        let mut seq = 0..self.cats.len();
        let mut cat : Option<&Cat> = None;
        for i in seq {
            if self.cats[i].name == name {
                cat = Some(&self.cats[i]);
                break;
            }
        }

        cat
    }

However, I'd like to know if there is a more elegant solution like this:

    fn get(&mut self, name : String) -> Option<&Cat> {
        for cat in &self.cats {
            if cat.name == name {
                break cat;
            }
        }

        None
    }

The second block of code is much shorter, cleaner, more intuitive, and easy to read.
However, it returns this error:

can only break with a value inside loop or breakable block

How can I fix this error so I can use the most elegant solution? Thanks! Or if there are other better options, let me now.

Thanks!

If you're returning the cat from the function, you can do

if cat.name == name {
    return Some(cat);
}

Though in this case, you can use Iterator::find:

fn get(&self, name: &str) -> Option<&Cat> {
    self.cats.iter().find(|c| c.name == name)
}
3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.