6 ms·
I don't understand; it seems to me try_block just simplifies let result: Result<i32, ParseIntError> = match ("1"::parse<int32>(), "2"::parse<int32
by setr 6y ago
I don't understand; it seems to me try_block just simplifies
let result: Result<i32, ParseIntError> =
match ("1"::parse<int32>(), "2"::parse<int32>(), "3"::parse<int32>()) {
(Ok(x), Ok(y), Ok(z) => Ok(x + y + z),
(Err(x), _, _) => Err(x),
(_, Err(y), _) => Err(y),
(_, _, Err(z)) => Err(z),
}
...
when the err is the same in every case (or coercible), by providing access to the ? without returning the function in full
It doesn't seem to me that it enables any new capability -- just a convenience.
- masklinn 6y agoThey also enable "early exiting" a block, so it's much easier to check for an error in the middle of a block: currently you'd need extra indentation or a `map` / `and_then` (which can lead to the compiler being unhappy as it has more flexibility within a function than across functions). So e.g. let result = { let a = a_thing(); let b = another_thing(); let c = a.foo(b)?; if c.a_thing() { Ok(c) } else { Err(…) } }; which currently has to be written let result = { let a = a_thing(); let b = another_thing(); a.foo(b).and_then(|c| if c.a_thing() { Ok(c) } else { Err(…) } ) } which doesn't look too bad for a simple example but can get out of hand if you need multiple thus, and as mentioned above the compiler can start being an issue if you work across-functions a lot.