I have the following code which contains a lot of nested if (some are Result
and some are Option
. Is it possible to reduce the nested if and have fewer indents?
Is there something like the post operator ? to simplify the code?
The code is focusing on the successful cases and ignore if there is anything wrong.
let res = client
.post(...
))
.header("Authorization", &config_env::get__api_token())
.header("Accept", "application/json")
.json(&task)
.send()
.await;
match res {
Ok(body) => {
println!("Succeed posting task {:?}", body);
if body.status() == reqwest::StatusCode::OK {
if let Ok(result) = body.json::<serde_json::Value>().await {
if let Some(code) = result.get("code") {
if let Some(code) = code.as_u64() {
if code != 200 {
if let Err(e) = github::issue::post_issue_comment(...
).await
{
eprintln!("{}", e);
}
}
}
}
}
} else {
eprintln!("Fail to send job with status code: {}.", body.status());
}
The approach I can think of is to use premature return like
if not_ok {
return;
}
if not_ok {
return;
}
...
but I still need to write a lot of return.