Created
April 11, 2020 15:00
-
-
Save bast/ea16e102bf7c674e16d4c687c284ef2a to your computer and use it in GitHub Desktop.
Show how to pass function as argument in Rust.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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