Higher order functions and closures
By now, we know how to use functions, like in the following example where function triples
changes our strength
variable, but only if the return value of the function triples
is assigned to the variable strength
:
// see code in Chapter 5/code/higher_functions.rs let mut strength = 26; println!("My tripled strength equals {}",triples(strength)); // 78 println!("My strength is still {}", strength); // 26 strength = triples(strength); println!("My strength is now {}", strength); // 78
Here, the function triples
is defined as the following function:
fn triples(s: i32) -> i32 { 3 * s }
In the preceding code, s
represents a value for the strength
variable.
Suppose our player smashes an amazing power stone, so that his strength is tripled and the resulting strength tripled again; we could write it as follows:
triples(triples(s))
We can also write a function to do this, but it would be even more general to have a function, let's call it again
, that could apply...