Function Pointers
Lesson 39 of 48 in Coddy's Rust for C++ Developers course.
C++ function pointers refer to functions with a compatible signature; capturing lambdas need an object to hold their environment. Rust fn pointer types likewise describe callable signatures without a captured environment. Function items and noncapturing closures can coerce to such pointers. A capturing Rust closure instead has its own environment-bearing type and is commonly accepted through a generic callable-trait bound. These are distinct choices from a trait object representing an entire policy object. A comparator passed to sorting must define a consistent ordering for the values being sorted. The examples order values by their last digit with distinct sort keys. They do not implement the task's predicate-and-transform pipeline, and the callbacks here compare two inputs rather than mapping one.
Complete standalone C++17 program:
#include <algorithm>
#include <iostream>
#include <vector>
bool by_last_digit(int a, int b) { return a % 10 < b % 10; }
int main() {
std::vector<int> values{24, 11, 32};
bool (*compare)(int, int) = by_last_digit;
std::sort(values.begin(), values.end(), compare);
for (int n : values) std::cout << n << ' ';
std::cout << '\n';
}Complete standalone Rust program:
use std::cmp::Ordering;
fn last_digit(a: &i32, b: &i32) -> Ordering { (a % 10).cmp(&(b % 10)) }
fn main() {
let mut values = vec![35, 10, 22];
let compare: fn(&i32, &i32) -> Ordering = last_digit;
values.sort_by(compare);
println!("{} {} {}", values[0], values[1], values[2]);
}Challenge
EasyIn callbacks.rs, implement even(n: i32) -> bool, positive(n: i32) -> bool, negate(n: i32) -> i32, and square(n: i32) -> i32. Zero is even but not positive. Implement transform::select(values: &[i32], keep: fn(i32) -> bool, map: fn(i32) -> i32) -> Vec<i32>: call the predicate on each original value, then map each accepted value and preserve order and duplicates. An empty slice returns an empty vector. Use the supplied callbacks, including callbacks defined by callers. solve reads mode even or positive followed by integers between -100 and 100. In even mode keep even values and negate them; in positive mode keep strictly positive values and square them. Return space-separated results or empty.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, callbacks.rs, transform.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod callbacks;
mod transform;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
assert!(callbacks::even(-14)); assert!(callbacks::even(0)); assert!(!callbacks::even(9));
assert!(!callbacks::positive(0)); assert!(!callbacks::positive(-3)); assert!(callbacks::positive(17));
assert_eq!(callbacks::negate(-23), 23); assert_eq!(callbacks::square(-11), 121);
fn below_four(n: i32) -> bool { n < 4 }
fn plus_seven(n: i32) -> i32 { n + 7 }
assert_eq!(transform::select(&[8, 3, -2, 3], below_four, plus_seven), vec![10, 5, 10]);
assert!(transform::select(&[], below_four, plus_seven).is_empty());
assert_eq!(transform::select(&[0, 2, 3], callbacks::even, callbacks::square), vec![0, 4]);
assert_eq!(transform::select(&[3, -2], below_four, plus_seven), vec![10, 5]);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for C++ Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap2Decisions and Loops
Boolean ConditionsIf ExpressionsMatch and EnumsLoops and RangesRecap: Charge Gate8Traits and Generic Code
Traits and ContractsGenerics and BoundsTrait ObjectsFunction PointersDerived Value SemanticsTesting Public ContractsScoring Contracts Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler