Crate extfn

Source
Expand description

§extfn - Extension Functions in Rust

extfn is a Rust library that implements extension functions, allowing any* freestanding function to be called as a.foo(b) instead of foo(a, b) just by adding #[extfn] and renaming the first parameter to self.

use extfn::extfn;
use std::cmp::Ordering;
use std::fmt::Display;

#[extfn]
fn factorial(self: u64) -> u64 {
    (1..=self).product()
}

#[extfn]
fn string_len(self: impl Display) -> usize {
    format!("{self}").len()
}

#[extfn]
fn sorted_by<T: Ord, F>(mut self: Vec<T>, compare: F) -> Vec<T>
where
    F: FnMut(&T, &T) -> Ordering,
{
    self.sort_by(compare);
    self
}

fn main() {
    assert_eq!(6.factorial(), 720);
    assert_eq!(true.string_len(), 4);
    assert_eq!(vec![2, 1, 3].sorted_by(|a, b| b.cmp(a)), vec![3, 2, 1]);
}

A list of all supported function forms can be found here.

§Prior Art

Extension functions are already implemented in Kotlin and C#.

As a Rust feature, extension functions have been proposed here, here, here, and here.

§Fine Print

  • Const functions are unsupported because of E0379
  • self: T::Assoc is unsupported

Attribute Macros§

extfn
Converts a regular function into an extension function.