#function #dynamically-typed #cell #foo #wrap #reference #mutable

any-fn

Dynamically-typed functions to represent any functions in Rust

7 releases

new 0.3.1 Jan 20, 2025
0.3.0 Jan 20, 2025
0.2.0 Jan 20, 2025
0.1.3 Jan 20, 2025

#706 in Rust patterns

Download history

58 downloads per month

Custom license

10KB
203 lines

any-fn

GitHub Action Crate License

Dynamically-typed functions via core::any::Any in Rust.

Examples

Calling a function with unboxed arguments

use any_fn::IntoAnyFn;
use core::{any::Any, cell::RefCell};

fn wrap<T: 'static>(x: T) -> RefCell<Box<dyn Any>> {
    RefCell::new(Box::new(x))
}

const fn foo(x: usize, y: usize) -> usize {
    x + y
}

assert_eq!(
    *foo.into_any_fn()
        .call(&[&wrap(1usize), &wrap(2usize)])
        .unwrap()
        .downcast::<usize>()
        .unwrap(),
    3
);

Calling a function with mutable reference arguments

use any_fn::IntoAnyFn;
use core::{any::Any, cell::RefCell};

fn wrap<T: 'static>(x: T) -> RefCell<Box<dyn Any>> {
    RefCell::new(Box::new(x))
}

fn foo(x: usize, y: &mut usize) {
    *y = x;
}

let x = wrap(0usize);

foo.into_any_fn().call(&[&wrap(42usize), &x]).unwrap();

assert_eq!(*x.borrow().downcast_ref::<usize>().unwrap(), 42);

License

MIT

No runtime deps