如何在Rust中引用函数?以实现块内函数转发为例
在Rust impl块中实现函数转发的正确方式
Rust不支持JavaScript那种直接赋值函数的语法,你没法用pub async fn test_hello -> test_hello;这种写法实现转发,必须通过显式调用目标函数来完成,下面是几种可行的场景:
1. 转发到同一impl内的方法
如果要转发的函数是当前impl里的其他方法,直接在转发函数体内调用它:
#[OpenApi] impl TestRoutesApi { // 实际逻辑的目标函数 async fn test_hello_inner(&self) -> PlainText<String> { PlainText(format!("hello")) } // 带OpenApi注解的转发函数 #[oai(path = "/test-hello", method = "get")] pub async fn test_hello(&self) -> PlainText<String> { self.test_hello_inner().await } }
2. 转发到外部函数
如果目标函数是外部定义的,只要签名匹配,直接调用即可:
// 外部的目标函数 async fn external_test_hello() -> PlainText<String> { PlainText(format!("hello from external")) } #[OpenApi] impl TestRoutesApi { #[oai(path = "/test-hello", method = "get")] pub async fn test_hello(&self) -> PlainText<String> { external_test_hello().await } }
3. 适配不同签名的情况
如果目标函数和转发函数签名不一致,需要手动做参数适配:
// 带参数的目标函数 async fn another_hello(name: &str) -> PlainText<String> { PlainText(format!("hello, {}", name)) } #[OpenApi] impl TestRoutesApi { #[oai(path = "/test-hello", method = "get")] pub async fn test_hello(&self) -> PlainText<String> { // 给目标函数传入默认参数 another_hello("guest").await } }
为什么你的写法不生效?
Rust的语法规则里,impl块中的普通方法必须有函数体(只有trait中的抽象方法可以省略),你尝试的那种“签名指向函数”的写法完全不符合Rust的函数定义规范,所以编译会报错。
内容的提问来源于stack exchange,提问作者Oliver Dixon
相关产品推荐
相关产品推荐

