From f70892a5bb01aed8d06548ad9a4785d01721bf7a Mon Sep 17 00:00:00 2001 From: bin liu Date: Sat, 10 Oct 2020 22:22:54 +0800 Subject: [PATCH] agent: use chain of Result to avoid early return Use rust `Result`'s `or_else`/`and_then` can write clean codes. And can avoid early return by check wether the `Result` is `Ok` or `Err`. Signed-off-by: bin liu --- src/agent/src/config.rs | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/src/agent/src/config.rs b/src/agent/src/config.rs index 227601f0b0..b46ab140ac 100644 --- a/src/agent/src/config.rs +++ b/src/agent/src/config.rs @@ -222,22 +222,16 @@ fn get_bool_value(param: &str) -> Result { let v = fields[1]; - // bool - let t: std::result::Result = v.parse(); - if t.is_ok() { - return Ok(t.unwrap()); - } - - // integer - let i: std::result::Result = v.parse(); - if i.is_err() { - return Ok(false); - } - - // only `0` returns false, otherwise returns true - Ok(match i.unwrap() { - 0 => false, - _ => true, + // first try to parse as bool value + v.parse::().or_else(|_err1| { + // then try to parse as integer value + v.parse::().or_else(|_err2| Ok(0)).and_then(|v| { + // only `0` returns false, otherwise returns true + Ok(match v { + 0 => false, + _ => true, + }) + }) }) }