What does Rust's unary || (parallel pipe) mean

2019-02-22 01:32发布

In Non-Lexical Lifetimes: Introduction, Niko includes the following snippet:

fn get_default3<'m,K,V:Default>(map: &'m mut HashMap<K,V>,
                                key: K)
                                -> &'m mut V {
    map.entry(key)
       .or_insert_with(|| V::default())
}

What does the || V::default() mean here?

标签: rust
2条回答
仙女界的扛把子
2楼-- · 2019-02-22 02:07

It is a closure with zero arguments. This is a simplified example to show the basic syntax and usage (play):

fn main() {
    let c = || println!("c called");
    c();
    c();
}

This prints:

c called
c called

Another example from the documentation:

let plus_one = |x: i32| x + 1;

assert_eq!(2, plus_one(1));
查看更多
混吃等死
3楼-- · 2019-02-22 02:16

It's a zero-argument lambda function.

查看更多
登录 后发表回答