Rust 如何将函数转发/别名/委托给方法?
我希望将函数转发到另一个模块中的方法,而不重复所有类型注释,也不手动传递参数。我该怎么做Rust 如何将函数转发/别名/委托给方法?,rust,Rust,我希望将函数转发到另一个模块中的方法,而不重复所有类型注释,也不手动传递参数。我该怎么做 mod other_mod; static client: other_mod::Client = other_mod::Client::new(); async fn search = client.search; // How to do this here? mod other\u mod: pub struct Client(); impl Client { pub fn new()
mod other_mod;
static client: other_mod::Client = other_mod::Client::new();
async fn search = client.search; // How to do this here?
mod other\u mod
:
pub struct Client();
impl Client {
pub fn new() -> Self {
Self()
}
pub async fn search(&self, query: &str) -> Result<Vec<SearchResultItem>> { ... }
}
pub-struct-Client();
impl客户端{
pub fn new()->Self{
Self()
}
发布异步fn搜索(&self,查询:&str)->结果{…}
}
在Rust中无法做到这一点。您的示例的主要问题是静态客户端
:
- 它无法创建,因为锈蚀不允许在
之前或之后使用main
- 出于线程安全原因,如果不使用
,则无法对其进行变异不安全的
如果将其
函数const
设置为新,则可以创建客户端
然后您可以将其设置为pub
,而无需转发该功能,用户只需调用CLIENT.search
pub static CLIENT: other_mod::Client = Client::new();
您还可以重构other_mod
,将search
功能公开为独立功能:
pub async fn search(query: &str) -> ...
然后用自己的方式转发:
pub use other_mod::search;
根本就没有在全局上转发方法的工具;Rust对全局变量的要求很苛刻,因为它们会带来各种各样的问题,所以我怀疑这种语法上的甜头会很快出现。真是太遗憾了。Go也这样做,但我认为这只是因为Go是不必要的冗长。