Iterate over a MutexGuard HashSet

Hi,

I was working on static HashSet. I ended up something like this.

#[macro_use] extern crate lazy_static;
use std::sync::Mutex;
use std::collections::HashSet;

lazy_static! {
    //#[derive(Debug)]
    static ref NAME: Mutex<HashSet<String>> = Mutex::new(HashSet::new());
}

fn main() {
    NAME.lock().unwrap().insert("James".to_owned());
    NAME.lock().unwrap().insert("Robert".to_owned());
    NAME.lock().unwrap().insert("John".to_owned());

    // Iterate over everything.
    for name in &NAME.lock().unwrap() {
        println!("{}", name);
    }
}

I can add elements into the set NAME, but when I try to iterate over the set it gives following error.

`&MutexGuard<'_, HashSet<String>>` is not an iterator
  --> src/main.rs:16:17
   |
16 |     for name in &NAME.lock().unwrap() {
   |                 ^^^^^^^^^^^^^^^^^^^^^ `&MutexGuard<'_, HashSet<String>>` is not an iterator
   |
   = help: the trait `Iterator` is not implemented for `&MutexGuard<'_, HashSet<String>>`
   = note: required because of the requirements on the impl of `IntoIterator` for `&MutexGuard<'_, HashSet<String>>`

I couldnt figure it out how to implement iterator trait to MutexGuard. Any thoughts?

for name in &NAME.lock().unwrap().iter() {
        println!("{}", name);
}
1 Like

Thank you! Following is working just fine.

#[macro_use] extern crate lazy_static;
use std::sync::Mutex;
use std::collections::HashSet;

lazy_static! {
    //#[derive(Debug)]
    static ref NAME: Mutex<HashSet<String>> = Mutex::new(HashSet::new());
}

fn main() {
    NAME.lock().unwrap().insert("James".to_owned());
    NAME.lock().unwrap().insert("Robert".to_owned());
    NAME.lock().unwrap().insert("John".to_owned());

    // Iterate over everything.
    for name in NAME.lock().unwrap().iter(){
        println!("{}", name);
    }
}

FYI, “for name in &*NAME.lock().unwrap() {” works, too.

4 Likes