1 个不稳定版本

0.1.0 2020年5月14日

#14 in #装饰器

MIT 许可证

8KB
139 代码行数(不含注释)

pydeco

Python风格的Rust装饰器


lib.rs:

类似Python的Rust装饰器

示例

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);
  • 带参数的装饰器
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);

依赖

~1.5MB
~37K SLoC