Possible to define generic closure?

后端 未结 2 1126
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 18:13

Does Rust support closures with generic return types? For example, I want to write something like this:

let get = |s: &str| -> Opt         


        
2条回答
  •  执笔经年
    2021-01-07 18:40

    The closure type is anonymous, so you won’t be able to write it down, and seems that the compiler won’t be able to infer it, so no luck.

    But is there any particular reason you want to use a closure? If I understood your question correctly, you just use this function to factor out some repeating actions, and you are not actually going to pass it around. Thus, an inner fn should work just fine. The downside is that you’ll have to pass all the values that used to be automatically captured by your closure.

    It would be something like that (the example is still pretty complex, so I didn’t try to compile it):

    fn from_row(result: &QueryResult, row: Vec) -> User {
        let mut map: HashMap<_, _> = row.into_iter().enumerate().collect();
    
        fn get(s: &str, result: &QueryResult, map: &mut HashMap<_, _>)
           -> T {
            result.column_index(s)
                .and_then(|i| map.remove(&i))
                .and_then(|x| from_value_opt(x)).ok()
        };
    
        User {
            id: get("id", &result, &mut map)
        }
    }
    

提交回复
热议问题