It’s kinda hard to write artificial example for this, and on small examples it does not look impressive. Good isolated examples will be:
fn do checks() {
if !check1() { panic!("check1") }
if early_return() { return; }
if !check2() { panic!("check2") }
// etc..
}
//lets make it fallable
fn do checks() -> Result<(), MyError> {
if !check1() { Err(MyError::Check1)? } // ugh, strange pattern
if early_return() { return Ok(()); } // I don't care about `Ok`, just end!
if !check2() { return Err(MyError::Check1); } // too verbose...
// etc..
Ok(()) // argh, always forget to add this line...
}
// with try fn
try fn do checks() -> Result<(), MyError> {
if !check1() { throw MyError::Check1; } // intention is crystal clear
if early_return() { return; } // with minimal changes
if !check2() { throw MyError::Check2; } // and easy to read
// etc..
// no weird (especially for beginners) `Ok(())` at the end
}
fn foo(val: Foo) -> Bar {
match val {
// several match arms
Foo::K => {
// do stuff
if condition() { return Bar::D; }
// do stuff
Bar::K
},
// more match arms
_ => panic!("unexpected variant"),
}
}
// Again lets make it fallible
fn foo(val: Foo) -> Result<Bar, MyError> {
// ehm, maybe I should write `let bar = match val { .. }; Ok(bar)`...
Ok(match val {
// several match arms
Foo::K => {
// do stuff
// again, always forget those returns buried in a middle
// of the function body, esp. if block was folded
// even worse if there is many such returns, repeating Ok(..)
// becomes quite annoying
if condition() { return Ok(Bar::D); }
// do stuff
Bar::K
},
// even more match arms
_ => Err(MyError::UnexpectedVariant)?,
})
}
// with `try fn`
try fn foo(val: Foo) -> Result<Bar, MyError> {
// no changes required, no `Ok` noise
match val {
// several match arms
Foo::K => {
// do stuff
// everything stays as is
if condition() { return Bar::D; }
// do stuff
Bar::K
},
// even more match arms
_ => throw MyError::UnexpectedVariant,
}
}
Isolated it does not seem like much, but when writing code I often get bitten by such papercuts, and it is not fun.