1 unstable release
0.1.0 | May 14, 2020 |
---|
#12 in #decorator
8KB
139 lines
pydeco
Python-like decorator in Rust
lib.rs
:
Python-like decorator for Rust
Example
use pydeco::deco;
fn logging<F>(func: F) -> impl Fn(i32) -> i32
where
F: Fn(i32) -> i32,
{
move |i| {
println!("Input = {}", i);
let out = func(i);
println!("Output = {}", out);
out
}
}
#[deco(logging)]
fn add2(i: i32) -> i32 {
i + 2
}
add2(2);
- Decorator with parameter
use pydeco::deco;
use std::{fs, io::Write};
fn logging<InputFunc: 'static>(
log_filename: &'static str,
) -> impl Fn(InputFunc) -> Box<dyn Fn(i32) -> i32>
where
InputFunc: Fn(i32) -> i32,
{
move |func: InputFunc| {
Box::new(move |i: i32| {
let mut f = fs::File::create(log_filename).unwrap();
writeln!(f, "Input = {}", i).unwrap();
let out = func(i);
writeln!(f, "Output = {}", out).unwrap();
out
})
}
}
#[deco(logging("test.log"))]
fn add2(i: i32) -> i32 {
i + 2
}
add2(2);
Dependencies
~1.5MB
~39K SLoC