#once #macro #function #macro-derive #derive

macro fn_once

This library provides a convenient derive macro for a once function

3 releases (breaking)

0.3.0 Sep 28, 2022
0.2.0 Sep 27, 2022
0.1.0 Sep 25, 2022

#71 in #once

MIT/Apache

8KB
53 lines

fn_once

This library provides a convenient derive macro for a once function.

CI Crates.io Licensed Twitter

fn_once = "0.3.0"

How to use,

use fn_once::once;

#[once]
fn print_once(name: &str) {
    println!("Hello! {}!", name);
}

#[once(or = { number })] // or = { block expression }
fn add_one_once(number: u32) -> u32 {
    count + 1
}

#[once(panic)]
fn panic_when_twice() { }

fn main() {
    print_once("World"); // print "Hello! World!"
    print_once("foo"); // no effect

    let mut number = 0;
    number = add_one_once(number); // 0 + 1 -> 1
    number = add_one_once(number); // no effect -> 1
    number = add_one_once(number); // no effect -> 1
    assert_eq!(number, 1);

    panic_when_twice();
    panic_when_twice(); // panic!
}

When you want to disable it,

[features]
default = ["once_off"]
once_off = []

# The point is that
# just `once_off` feature is turned on.

Dependencies

~1.5MB
~37K SLoC