Idiomatic way of returning a value from a for-loop

Hi there,

I have a very simple struct called 'User' over which I am iterating in a for-loop looking for a specific user.
The function returns a Option, as it is possible that no user will be found.
The problem I'm having is that I'm getting a compilation failure: expected (), found enum std::option::Option

Code is the following:

pub struct User {
    pub id: u8,
    pub name: String


fn get_name_by_id(id: u8, users: &Arc<Mutex<Vec<User>>>) -> Option<String> {
    let user_vec = users.lock().unwrap();
    for user in user_vec.iter() {
        if == id {

Is there an elegant way to solve this problem?

PS: This is my first post here, I hope the code will be formatted correctly!

There is find method on Iterator designed to do exactly this. If you want to write the same code by hand without iterator adapter, you can check the source.


Thank you for your fast reply!

Looks much nicer that way too!

You're welcome! In fact, Iterator API is rather rich, as you can see by the docs, so in many cases you may be able to do what you need without for loops at all. And if you really need it, well, return keyword is always here (but in the current case the iterator method would be clearly more idiomatic).

While it's not exactly relevant to your question, you may want to replace String::from( with As well as being less keystrokes, it makes it more obvious that you're returning a copy of the user's name and not doing anything special.

1 Like

Just so you get an answer to your actual question, all you need to do is use the return statement in your for loop, like return Some(;.

1 Like

Thank you for your answers, I'm (probably obviously) just starting to learn Rust.
@Michael-F-Bryan Thanks! I somehow thought only types with the Copy-Trait have clone() available.
@radix Good to know, one day I might find myself in a more complex situation, where this will come in handy.

1 Like

It's not the Copy trait, but Clone trait, which is implemented by many standard types, including String.

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