Skip to content

Instantly share code, notes, and snippets.

@indykish
Created December 29, 2017 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indykish/a7d71f9f8f21bf144ba458aab8811098 to your computer and use it in GitHub Desktop.
Save indykish/a7d71f9f8f21bf144ba458aab8811098 to your computer and use it in GitHub Desktop.
Clone Fn closure using Arc in rust lang
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