Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is | | symbol in function call in rust?

While going through rust documentation I found below code

let k = 21;
let x : Result<_, &str> = Ok("foo");
assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);

What exactly is |e| & |v| in last line ? why it is required?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The .map_or_else functions take a closure as a parameter.
A closure is an anonymous function that can optionally capture the environment where they are defined. The syntax to define a closure is

let c = |x| println!(x + 2);

This takes 1 parameters which is mapped to the x variable.l
Calling x(2) will print 4, calling x(4) will print 6.

Similarly |e| k * 2 and |v| v.len() is
also a closure. They also take 1 parameter, e and k which are the parameter names whose values will be filled by the .map_or_else function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading