Created
December 29, 2017 10:45
-
-
Save indykish/a7d71f9f8f21bf144ba458aab8811098 to your computer and use it in GitHub Desktop.
Clone Fn closure using Arc in rust lang
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
use std::sync::Arc; | |
use std::fmt; | |
type Fp = Box<Fn(i8, i8) -> i8 + Send + Sync>; | |
#[derive(Clone)] | |
struct WithCall { | |
fp: Arc<Fp>, | |
} | |
impl WithCall { | |
pub fn new(fp: Fp) -> WithCall { | |
WithCall { fp: Arc::new(fp) } | |
} | |
pub fn run(&self, a: i8, b: i8) -> i8 { | |
(*self.fp)(a, b) | |
} | |
} | |
impl fmt::Display for WithCall { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "Cloning ... your Fn closure. Done !!!") | |
} | |
} | |
fn main() { | |
let adder = WithCall::new(Box::new(|a: i8, b: i8| a + b)); | |
println!("Ran adder {}", adder.run(1, 2)); | |
let add_b = adder.clone(); | |
println!("{}", add_b); | |
println!("Ran adder cloned {}", add_b.run(2, 4)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment