我想编写一个调用 API 的函数,并将端点作为 &str 和它应该放入主体的数据,我的函数如下所示:
async fn call_clientd<T>(query : &str, json : &T) -> Result<ResBody, reqwest::Error>
where T : serde::ser::Serialize + ?Sized
{
let res = Client::new()
.post(format!("{}{}", "http://127.0.0.1:8080/", query))
.json(json)
.send()
.await?;
let res : ResBody = res.json().await?;
Ok(res)
}
我需要用 String 和 u64 调用它:
let (res, raw) = match &args.command {
Commands::Info { raw } => {
(call_clientd("info", ""), raw)
},
Commands::Pending {raw} => {
(call_clientd("pending", ""), raw)
},
Commands::Spend {amount, raw} => {
(call_clientd("spend", amount), raw)
},
Commands::Reissue {coins, raw, validate} => {
(call_clientd("reissue", coins), raw)
},
Commands::Events { raw} => {
(call_clientd("events", ""), raw)
},
};
但是编译器总是推断(在这种情况下)该函数需要一个&str*
......有没有可能的方法来做到这一点?我的替代方案非常多余。
我得到的错误似乎将匹配臂作为问题而不是函数本身(之前没有看到):
error[E0308]: `match` arms have incompatible types
--> mint-client/src/bin/client-cli/main.rs:64:13
|
56 | let (res, raw) = match &args.command {
| ______________________-
57 | | Commands::Info { raw } => {
58 | | (call_clientd("info", ""), raw)
| | ------------------------------- this is found to be of type `(impl Future<Output = Result<ResBody, reqwest::Error>>, &bool)`
59 | | },
60 | | Commands::Pending {raw} => {
61 | | (call_clientd("pending", ""), raw)
| | ---------------------------------- this is found to be of type `(impl Future<Output = Result<ResBody, reqwest::Error>>, &bool)`
... |
64 | | (call_clientd("spend", amount), raw)
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `str`, found `u64`
... |
71 | | },
72 | | };
| |_____- `match` arms have incompatible types
|
这里的问题是它call_clientd
是一个async
函数,这意味着它确实返回了一些实现Future<Output = Result<ResBody, reqwest::Error>>
. 当你对 使用不同的类型参数时call_clientd
,你会得到不同的(不兼容的)返回的期货。
错误中显示“expected str
, found u64
”的部分有点误导:编译器看到第一个匹配臂返回了未来,call_clientd::<str>
所以它告诉你它想要相同的未来,而是找到了未来call_clientd::<u64>
。
由于您不太可能想要未来本身,因此您可以简单await
地获取底层Result<ResBody, reqwest::Error>
:
let (res, raw) = match &args.command {
Commands::Info { raw } => {
(call_clientd("info", "").await, raw)
},
Commands::Pending {raw} => {
(call_clientd("pending", "").await, raw)
},
Commands::Spend {amount, raw} => {
(call_clientd("spend", amount).await, raw)
},
Commands::Reissue {coins, raw, validate} => {
(call_clientd("reissue", coins).await, raw)
},
Commands::Events { raw} => {
(call_clientd("events", "").await, raw)
},
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句