Issue
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?
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.
Calling c(2)
will print 4, calling c(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.
Answered By - Arijit Dey Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.