Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 973
Calder Avatar asked May 02 '16 17:05

Calder


People also ask

What does || do in Rust?

|| Ok(HelloWorld) is a closure that takes 0 arguments and returns Result<R, hyper::Error> .

What does pipe mean in Rust?

“Pipes” are used to defined closures https://doc.rust-lang.org/book/second-edition/ch13-01-closures.html. _ is used when there is an input argument that you simple don't use and the way to tell the compiler about it is to add a _ you can also do _my_var as well for the same result.


2 Answers

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)); 
like image 143
Arjan Avatar answered Sep 20 '22 20:09

Arjan


It's a zero-argument lambda function.

like image 34
Calder Avatar answered Sep 17 '22 20:09

Calder