intermediateFunctions
Function Pointers
Use function pointers (fn) as arguments and return values.
Function Pointers
Use function pointers (fn) as arguments and return values.
Difficulty
Intermediate
Code
rust
fn add(a: i32, b: i32) -> i32 { a + b }
fn mul(a: i32, b: i32) -> i32 { a * b }
fn apply(f: fn(i32, i32) -> i32, a: i32, b: i32) -> i32 {
f(a, b)
}
fn get_op(op: &str) -> fn(i32, i32) -> i32 {
match op {
"add" => add,
"mul" => mul,
_ => add,
}
}
fn main() {
println!("add: {}", apply(add, 3, 5));
println!("mul: {}", apply(mul, 3, 5));
let op = get_op("mul");
println!("op: {}", op(4, 6));
}Explanation
Function pointers (fn) are concrete types for function values.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the functions category to build a complete understanding of this topic.