Ways to make a function return named methods?

sorry, coming from planet Javascript.
Some usual pattern I freakin love is:

function give_me_fn(){

  return {
    do: () => {},
    that: () => {},
  }
}

const { do, that } = give_me_fn()

Now what I've seen is people do Struct and Impl.
Any other patterns? Should I do it with Struct Impl too?

I just want to make a crate with a series of async method calls.

thx

You can declare a struct and its impl inside a function, if you want, but that doesn't let them capture variables. (I've given some thought about whether a macro could add this feature, and it could do some cases, but the details of getting it to work adequately, and the cases in which it would work, are actually quite tricky.)

But if you're going to pack inside the function and unpack when you call it, then that sounds like a struct with a bunch of Fn fields, that aren't strictly methods.

Trying to translate any OO-code to Rust is the worst idea any beginner can get, but there are some kinds of user-defined types in Rust: struct, enum and union. You can read about these ones in the reference, pages 10.1.8..=10.1.10.

1 Like

Here is a fairly direct translation of your code, with async fns specifically. (Whether this is a good idea is another question.)

use async_fn_traits::AsyncFn0;

struct Fns<F, G> {
    dew: F,
    that: G,
}

fn give_me_fn() -> Fns<impl AsyncFn0<Output = ()>, impl AsyncFn0<Output = i32>> {
    return Fns {
        dew: || async {},
        that: || async { 100 },
    };
}

fn main() {
    let Fns { dew, that } = give_me_fn();
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.