anonymous-trait

Crates.ioanonymous-trait
lib.rsanonymous-trait
version0.1.3
sourcesrc
created_at2023-12-21 06:55:29.058412
updated_at2024-01-10 09:12:15.998613
descriptionAnonymous trait implementation with capturing the environment
homepage
repositoryhttps://github.com/ryo33/anonymous-trait
max_upload_size
id1076523
size42,370
Ryo Hirayama (ryo33)

documentation

README

anonymous-trait

Anonymous trait implementation with capturing the environment

Example

trait Cat {
    fn meow(&self) -> String;
    fn set_name(&mut self, new: String);
    async fn meow_async(&self) -> String;
}

#[tokio::main]
async fn main() {
    let name = "mock";

    #[anonymous_trait::anonymous_trait(let mut cat_mock = "default".into())]
    impl Cat for String {
        fn meow(&self) -> String {
            name.to_string()
        }

        fn set_name(&mut self, new: String) {
            *self = new;
        }

        async fn meow_async(&self) -> String {
            "meow".to_string()
        }
    }

    run(&mut cat_mock).await;
}

async fn run(cat: &mut impl Cat) {
    println!("meow: {}, expected: mock", cat.meow());
    cat.set_name("hi".to_string());
    println!("meow_async: {}, expected: meow", cat.meow_async().await);
}
Commit count: 2

cargo fmt