Changing the `iter` chain to use` and_then`, etc.

I have a function that looks like this:

type Attributes = HashMap<String, json::Json>; type Store = Arc<RwLock<HashMap<String, RwLock<Attributes>>>>; fn get(store: &Store, key: &str) -> Option<Attributes> { store.read().iter() .filter_map(|g| (*g).get(key) ) .filter_map(|v| v.read().ok() ) .map(|v| (*v).clone() ) .next() } 

This compiles and works fine. However, for my own edification, I tried to change this to use the standard Result / Option methods (without converting LockResult to Iter ), something like:

 store.read().ok() .and_then(|g| (*g).get(key) ) .and_then(|v| v.read().ok() ) .map(|v| (*v).clone() ); 

But that tells me that g does not live long enough . I tried to add ref and as_ref in different places, but I can not compile it. What am I missing?

I know that I can make it work like:

  store.read().ok() .and_then(|g| { (*g).get(key) .and_then(|v| v.read().ok() ) .map(|v| (*v).clone() ) }) 

But I would like to be able to bind it as in the case of Iter .

+5
source share
1 answer

Well, the compiler is really messing with me tonight.

I got this spell to compile:

 fn get(store: &Store, key: &str) -> Option<Attributes> { let r = store.read(); let x = r.as_ref().ok() .and_then(|g| (*g).get(key) ) .and_then(|v| v.read().ok() ) .map(|v| (*v).clone() ); x } 

If you enter the string r or x , you again get another error does not live long enough . I’m not sure why, because, in principle, the security guard’s lock should remain active as temporary until the end of the statement.

+3
source

Source: https://habr.com/ru/post/1240452/


All Articles