4

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>> { ... }

}

2 Answers 2

5

There is no way to do that in Rust.

Sign up to request clarification or add additional context in comments.

3 Comments

That's a shame. Go does this too, but I assumed it was just because Go is needlessly verbose.
For people finding this in search of a compiler optimization barrier: stackoverflow.com/a/60720419/7204912
3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.