#async #macro #extension #boilerplate #definition #traits #self

macro extension-fn

No boilerplate code for extension function definitions

4 stable releases

1.2.0 May 19, 2023
1.1.1 May 18, 2023
1.0.0 Apr 12, 2023

#788 in Procedural macros

MIT and GPL-3.0 licenses

10KB
142 lines

This crate provides the extension_fn macro for extending types with extension functions.

Example

For example there is a count_numbers extension function for str:

/// Replacement for:
/// Sealed is internal trait that used to provide only one implementation of trait and nobody outside module can implement this
/// pub trait CountNumbers: Sealed {
///     fn count_numbers(&self) -> u32;
/// }
/// impl CountNumbers for str {
///     fn count_numbers(&self) -> u32 { ... }
/// }
#[extension_fn(str)]
pub fn count_numbers(&self) -> u32 {
     self.chars().fold(0, |count, char| {
        if char.is_numeric() {
         count + 1
        } else {
           count
        }
    })
}

You can extend using async functions by adding async-trait to your dependencies:

[dependencies]
async-trait = "*"

Also you can extend types that matching trait bound:

#[extension_fn(trait AsRef<str>)]
pub fn count_numbers(&self) { ... }

lib.rs:

No boilerplate code for extension function definitions.

Dependencies

~325–780KB
~19K SLoC