#extension #traits #impl #methods #custom

extension-traits

用于轻松定义临时代码/一次性扩展特性的注释

4 个版本 (稳定)

2.0.0 2024 年 7 月 11 日
2.0.0-rc12024 年 7 月 10 日
1.0.1 2022 年 1 月 18 日

#1483Rust 模式

Download history 15802/week @ 2024-05-03 19409/week @ 2024-05-10 19577/week @ 2024-05-17 20699/week @ 2024-05-24 22115/week @ 2024-05-31 16472/week @ 2024-06-07 17217/week @ 2024-06-14 24181/week @ 2024-06-21 21325/week @ 2024-06-28 14420/week @ 2024-07-05 15684/week @ 2024-07-12 13178/week @ 2024-07-19 14735/week @ 2024-07-26 10615/week @ 2024-08-02 12963/week @ 2024-08-09 17308/week @ 2024-08-16

58,733 每月下载量
用于 45 个 crate (4 个直接使用)

Zlib OR MIT OR Apache-2.0

15KB
53

::扩展-特性

用于轻松定义 临时 / 一次性扩展特性的注释。

Repository Latest version Documentation MSRV unsafe forbidden License CI

示例

  • 另外

    #[macro_use]
    extern crate extension_traits;
    
    #[extension(trait Also)]
    impl<T> T {
        fn also (mut self, f: impl FnOnce(&mut Self))
          -> Self
        {
            f(&mut self);
            self
        }
    }
    
    fn main ()
    {
        use ::std::{collections::HashMap, ops::Not};
    
        let /* immut */ map = HashMap::with_capacity(2).also(|m| {
            m.insert("foo", 42);
            m.insert("bar", 27);
        });
        assert!(map.contains_key("foo"));
        assert!(map.contains_key("bar"));
        assert!(map.contains_key("baz").not());
    }
    
  • WithPath

    #[macro_use]
    extern crate extension_traits;
    
    use ::std::{error::Error, path::{Path, PathBuf}};
    
    #[extension(trait WithPath)]
    impl PathBuf {
        fn with (mut self, segment: impl AsRef<Path>)
          -> PathBuf
        {
            self.push(segment);
            self
        }
    }
    
    fn main ()
      -> Result<(), Box<dyn Error>>
    {
        let some_dir = PathBuf::from(::std::env::var("MY_LIB_SOME_DIR")?);
        // Contrary to chaining `.join()`, this reuses the memory!
        let some_subdir = some_dir.with("some").with("sub").with("dir");
        //
        Ok(())
    }
    
  • 上下文

    #[macro_use]
    extern crate extension_traits;
    
    use ::std::{error::Error, fmt::Display};
    
    #[extension(trait Context)]
    impl<Ok, Err : Display> Result<Ok, Err> {
        fn context (self, prefix: impl Display)
          -> Result<Ok, String>
        {
            self.map_err(|err| format!("{}: {}", prefix, err))
        }
    }
    
    fn main ()
      -> Result<(), Box<dyn Error>>
    {
        let file_contents =
            ::std::fs::read_to_string("some/file")
                .context("Error when opening some/file")?
        ;
        //
        Ok(())
    }
    

https://docs.rs/extension-trait 类似,但针对以下

特性

  • 支持泛型(见 Context

  • 搜索/grep 'trait' TraitName' 友好!

依赖项

~1.5MB
~35K SLoC