Closures as function arguments

Consider the following code:

fn call_with_three<F>(some_closure: F) -> i32 where F : Fn(i32) -> i32
{
some_closure(3)
}
fn main()
{
let answer = call_with_three(|x| x + 10 );
println!("{}", answer);
}
The code for this section can be found in Chapter 11/close_fn_args.

We call call_with_three and pass in the closure as the parameter. The function call_with_three takes a parameter of type F. So far, it's no different from any other function taking a generic value as an argument. However, we're binding F to be a function of type i32, which returns a value of type i32. We have created an inline function to be a parameter for a called function! When the code is compiled, we get the expected value on screen—13:

Figure 8
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset