Menu
CoddyTech

Function Pointers

Lesson 39 of 48 in Coddy's Rust for Java Developers course.

Java functional interfaces give lambdas and method references a target type such as IntUnaryOperator. Rust has both function-pointer types and closure traits. A function item can coerce to a pointer such as fn(char) -> bool. A noncapturing closure can also coerce to a compatible function pointer, but a closure that needs captured state cannot generally do so.

Function-pointer parameters describe an exact callable signature without hidden captured environment. Generic bounds using Fn, FnMut or FnOnce accommodate closures according to how they access captures and whether they consume them. The example passes a predicate for ASCII letters and applies it once. It does not iterate a collection, filter values, or map arithmetic results.

Java: complete program

class Main {
    static boolean asciiLetter(int c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }
    public static void main(String[] args) {
        java.util.function.IntPredicate test = Main::asciiLetter;
        System.out.println(test.test('7'));
    }
}

Rust: complete program

fn ascii_letter(c: char) -> bool { c.is_ascii_alphabetic() }
fn main() {
    let test: fn(char) -> bool = ascii_letter;
    println!("{}", test('7'));
}

Pitfall: a Java lambda capturing an effectively final variable is valid, but the analogous capturing Rust closure may not fit a fn pointer parameter.

challenge icon

Challenge

Easy

In 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));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Java Developers

Practice on your own: Online Rust compiler