It's not because its always executed, which defeats the purpose. I cover both versions in the post - perhaps it wasn't being clear enough :/
-
-
Replying to @yoshuawuyts
`or_else` takes a closure which is only executed if the Result is an Err and which returns a new Result. i think it's actually the same as your `unwrap_or_result` idea https://doc.rust-lang.org/std/result/enum.Result.html#method.or_else …
1 reply 0 retweets 1 like -
Replying to @goto_bus_stop
Ahhhh, yes okay - that looks a lot closer! Looks like it only applies to Result types though, not Option types. So still don't think it would solve this case. But it's getting closer!
1 reply 0 retweets 0 likes -
Replying to @yoshuawuyts
Option has or_else which you can return another Option from, and `ok_or_else(fn)` which turns an Option<T> into a Result<T, E> in a similar way https://doc.rust-lang.org/std/option/enum.Option.html#method.ok_or_else …
1 reply 0 retweets 0 likes -
Replying to @goto_bus_stop
Yeah, but I'm still not seeing any way where we can handle errors inside the None branch. How would the initial example be expressed with these statements? I feel like I'm missing something obvious?
1 reply 0 retweets 0 likes -
Replying to @yoshuawuyts
let node = self.cache.get(key) // Option<K> .ok_or_else(|| self.db.get(key))?; // Result<K, E> can be ?-ed // node is now a K
1 reply 0 retweets 1 like -
Replying to @goto_bus_stop
Ahhh, yeah I see where you're going. But believe there's a mistake there. The type returned by the closure will end up being: Result<Result<K, E>, E> Which is incompatible with the return type from `self.cache.get()`. So we'd still need to do `self.db.get(key).unwrap()` :(
1 reply 0 retweets 0 likes -
Replying to @yoshuawuyts
No, the closure's Result *is* the return value of x.ok_or_else if x is None, it doesn't get wrapped
2 replies 0 retweets 0 likes -
Replying to @goto_bus_stop
This is what I meant: you're getting two different return types by doing it this way. Which means calling `.unwrap()` might cause a panic. Repro https://github.com/yoshuawuyts/repro-or-else … Included screens for output both with type annotations and compiled. Note the different type sigs in 2.pic.twitter.com/FsQS9a9Oer
1 reply 0 retweets 0 likes -
Replying to @yoshuawuyts
Argh, yes it does Err(err()) and I misremembered. Thanks for your patience
1 reply 0 retweets 1 like
Haha, all good! Enjoyed it & learned a bunch too! :D
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.