【发布时间】:2022-01-19 10:46:24
【问题描述】:
我有这段代码,它本质上需要返回一个字符串。我正在迭代一个 JSON 响应,并且值(我感兴趣的字符串)在其中很深,所以我需要一个 for 循环和一个 if/else。这里的问题是这些循环的范围{}。我感兴趣的值在作用域结束后立即销毁,我需要返回的值变成(),因为函数返回一个Result<String, reqwest::Error>
这就是我的意思:
pub fn get_sprint() -> Result<String, reqwest::Error> {
//The code to get the JSON response works fine. I store it in the variable called `get_request`. Here's the issue I am having:
if get_request.status() == 200 {
let resp: Response = get_request.json()?;
for r in resp.value {
if r.attributes.timeFrame == "current" {
return Ok(r.name.to_string()); // THIS PLACE. I know the value is getting destroyed right after the scope ends, but I can't think of a way for it to not do that.
}
}
} else {
Ok(format!("Encountered error - {}", get_request.status().to_string()))
}
}
当我运行上面的代码时,我得到了这个:
error[E0308]: mismatched types
--> src\getLatestSprint.rs:71:9
|
37 | pub fn get_sprint() -> Result<String, reqwest::Error> {
| ------------------------------ expected `Result<std::string::String, reqwest::Error>` because of return type
...
71 | / for r in resp.value {
72 | | if r.attributes.timeFrame == "current" {
73 | | return Ok(r.name.to_string());
74 | | }
75 | | }
| |_________^ expected enum `Result`, found `()`
|
= note: expected enum `Result<std::string::String, reqwest::Error>`
found unit type `()`
For more information about this error, try `rustc --explain E0308`.
嗯,是的。我知道它需要一个结果,并得到()。我怎样才能克服这个问题?
【问题讨论】:
-
为什么不在
for循环结束后返回Error(blabla)?这有什么问题 -
至于问题:问问自己,当状态码为200,但响应值没有
timeframe == "current"的属性时,你的函数返回了什么? -
我很抱歉。我删除了错误的屏幕截图并添加了文本。