clonesure 0.3.0

A helper macro to create closures which will clone its environment.
Documentation
  • Coverage
  • 33.33%
    1 out of 3 items documented1 out of 1 items with examples
  • Size
  • Source code size: 10.17 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 262.47 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 11s Average build duration of successful builds.
  • all releases: 11s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • DiscreteTom/clonesure
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • DiscreteTom

Clonesure

Crates.io Crates.io docs.rs

A helper macro to create closures which will clone its environment.

Install

Add the following line to your Cargo.toml file:

clonesure = "0.3.0"

Getting Started

When define parameters of a closure, use @var to clone a variable, use @mut var to clone a mutable variable.

Cloned variables must be in front of closure parameters.

E.g.:

cc!(|@a, @mut b, c| a + b + c)

will be translated to:

{
  let a = a.clone();
  let mut b = b.clone();
  move |c| a + b + c
}

Examples

use clonesure::cc;

fn main() {
  // `cc` will implicitly move its environment
  let s1 = String::from("111");
  let s2 = String::from("222");
  assert_eq!(
    // implicitly move s1 into the closure
    // brackets of the closure's body are optional
    cc!(|| s1)(),
    "111"
  );
  assert_eq!(
    // explicitly move s2 into the closure
    cc!(move || s2)(),
    "222"
  );

  // clone one var
  let s1 = String::from("111");
  assert_eq!(
    // clone s1 into the closure
    cc!(|@s1| s1)(),
    "111"
  );
  assert_eq!(
    s1, // the original s1 is still alive
    "111",
  );

  // clone many vars
  let s1 = String::from("111");
  let s2 = String::from("222");
  assert_eq!(cc!(|@s1, @s2| s1 + &s2)(), "111222");

  // clone var mut
  let s1 = String::from("111");
  let s2 = String::from("222");
  assert_eq!(
    cc!(|@mut s1, @s2| {
      s1 = s1 + &s2;
      s1
    })(),
    "111222"
  );

  // with closure params
  // cloned vars must be in front of closure params
  let s1 = String::from("111");
  let s2 = String::from("222");
  let s3 = String::from("333");
  assert_eq!(
    cc!(|@mut s1, @s2, s3| {
      s1 = s1 + &s2 + s3;
      s1
    })(&s3),
    "111222333"
  );

  // param type, param pattern, return type
  let s1 = String::from("111");
  let s2 = String::from("222");
  let s3 = String::from("333");
  let s4 = 444;
  assert_eq!(
    cc!(|@mut s1, @s2, s3: String, &s4| -> String {
      s1 = s1 + &s2 + &s3;
      format!("{}{}", s1, s4)
    })(s3, &s4),
    "111222333444"
  );
}

CHANGELOG