Matt Joiner
Matt Joiner

Reputation: 118520

How can I forward/alias/delegate a function to a method?

I want to forward a function to a method in another module, without repeating all the type annotations, and without manually passing the parameters over. How would I do this?

mod other_mod;

static client: other_mod::Client = other_mod::Client::new();

async fn search = client.search; // How to do this here?

mod other_mod:

pub struct Client();

impl Client {
    pub fn new() -> Self {
        Self()
    }    

    pub async fn search(&self, query: &str) -> Result<Vec<SearchResultItem>> { ... }

}

Upvotes: 4

Views: 1701

Answers (2)

Matthieu M.
Matthieu M.

Reputation: 299820

The main issue with your example, is the static Client:

  • It cannot be created, because Rust does not allow life before or after main.
  • It cannot be mutated without using unsafe, for thread-safety reasons.

You can create the Client if you make its new function const.

Then you can make it pub and there is no need to forward the function at all, users can simply call CLIENT.search.

pub static CLIENT: other_mod::Client = Client::new();

You can also refactor other_mod to expose the search function as free-standing:

pub async fn search(query: &str) -> ...

And then forward it in your own:

pub use other_mod::search;

There are simply no facilities to forward methods on globals; Rust is harsh on global variables, because they open all kinds of issues, so I doubt that such syntactic sugar will come any time soon.

Upvotes: 3

Stargateur
Stargateur

Reputation: 26727

There is no way to do that in Rust.

Upvotes: 5

Related Questions