Hacker News new | ask | show | jobs
by the__alchemist 403 days ago
Something I use for situations where nesting is getting out of hand. Probably not idiomatic but, I find it practical in these cases.

  if param.is_none() {
    // Handle, and continue, return an error etc
  }
  let value = param.as_ref().unwrap(); // or as_mut
  // Use `value` as normal.
2 comments

You can rewrite it using let-or-else to get rid of the unwrap, which some would find to be more idiomatic.

    let value = Some(param.as_ref()) else {
      // Handle, and continue, return an error etc
    }
    // Use `value` as normal.
Small nit: the Some() pattern should go on the left side of the assignment:

    let Some(value) = param.as_ref() else {
      // Handle, and continue, return an error etc
    }
    // Use `value` as normal.
That part intrigued me about the article: I hadn't heard of that syntax! Will try.
Any advantages of this over let-else?
Update: No, I don't think so. Just tried Let Else... I like it more than the ex I posted.

That said, much like it took me a while to Grok if let syntax... this will be a struggle. See the other example in this thread where the one suggesting it reversed the syntax. That will take a bit to get right...

I wasn't familiar with let-else...
I just learned about it through this article, myself!