Skip to content

Instantly share code, notes, and snippets.

@bast
Created April 11, 2020 15:00
Show Gist options
  • Save bast/ea16e102bf7c674e16d4c687c284ef2a to your computer and use it in GitHub Desktop.
Save bast/ea16e102bf7c674e16d4c687c284ef2a to your computer and use it in GitHub Desktop.
Show how to pass function as argument in Rust.
struct Point {
x: f64,
y: f64,
}
fn custom(p1: &Point, p2: &Point) -> f64 {
let dx = p2.x - p1.x;
let dy = p2.y - p1.y;
let d = dx * dx + dy * dy;
return d.sqrt();
}
fn distance(f: fn(&Point, &Point) -> f64) -> f64 {
let p1 = Point { x: 1.0, y: 1.0 };
let p2 = Point { x: 1.0, y: 4.0 };
let d = f(&p1, &p2);
return d;
}
fn main() {
let d = distance(custom);
dbg!(d);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment