nannou icon indicating copy to clipboard operation
nannou copied to clipboard

making default functions to closures

Open thinkrapido opened this issue 3 years ago • 4 comments

I like to suggest a pull request to make the default functions like ModelFn, UpdateFn, etc... usable as a closure.

Related: https://github.com/nannou-org/nannou/issues/793

It is a very easy fix and we gain much more flexibility in developing complex programs.

A call would be via an macro

fn main() {
    nannou::sketch(view!(|app: &App, frame: Frame| {
        //...
    })).run()
}

and to respective functions.

Also read, how it is meant: https://medium.com/@romeo-disca/smart-pointers-in-rust-158046006f15

thinkrapido avatar Nov 28 '22 13:11 thinkrapido

all the examples need to be improved due to this pull request

thinkrapido avatar Nov 28 '22 13:11 thinkrapido

Using closures instead of fns would make things easier, indeed. In my personal project, for example, I am using thread_local! to pass a pre-computed value to the fn. However, there are certain things in your PR I do not understand:

  • Why are the types Arc<dyn Fn(...)>? Shared Fn closures are a pretty rare thing in Rust. You probably want to use Box<dyn FnMut(...)>.
  • What is the reason to use macros? You could just use regular generics instead e.g. fn foo(foo_fn: impl FnMut()) { let boxed = Box::new(foo_fn) }. If you want some kind of name aliasing you could do the following:
trait FooFn {
    fn foo(&mut self);
}

impl<F: FnMut()> FooFn for F {
    fn foo(&mut self) {
        self()
    }
}

fn consumes_foo(foo_fn: impl FooFn) {
    let boxed: Box<dyn FooFn> = Box::new(foo_fn);
}

fn calls_foo() {
    consumes_foo(|| {})
}

Woyten avatar Nov 30 '22 20:11 Woyten

@thinkrapido Did you make any progresses with this PR? I just ran into the issue of passing state from outside nannou::app(), which it would solve.

abey79 avatar Feb 21 '23 09:02 abey79

@abey79 , no I didn't. For me the pull request solved to problem.

thinkrapido avatar Feb 28 '23 20:02 thinkrapido