Don’t say anyway, say anyhow

  • magic_lobster_party@fedia.io
    link
    fedilink
    arrow-up
    22
    ·
    1 year ago

    Unwrap means it forces to evaluate the result as an ”ok value”. If it’s an ”error value”, it will crash. It’s a bad practice to rely on it, as it’s one of the most common ways a Rust programs can crash.

    Rust offers many options to handle errors that don’t risk crashing. For example, unwrap_or_default, which means ”if it’s an error value, use the default value for this type, such as 0 for integers”

    • Korne127@lemmy.world
      link
      fedilink
      arrow-up
      11
      ·
      1 year ago

      I mean using unwrap is not bad practice if the value is guaranteed to not be none, which can happen frequently in some applications.

        • Korne127@lemmy.world
          link
          fedilink
          arrow-up
          1
          ·
          11 months ago

          A very typical use-case would be getting something from a HashMap (or a Vector) and calling unwrap because you know it must exist (as you got a reference to the index or object that must be valid in the HashMap or Vector).
          Or if you call a function that returns Option<…> depending on the current state and you know that it must return Some(…) in the current situation.

    • sirdorius@programming.dev
      link
      fedilink
      arrow-up
      3
      ·
      1 year ago

      Unwrap is good for prototyping and trying out stuff fast, but it generally shouldn’t make it past a code review onto main, unless you’re very sure

      • dejected_warp_core@lemmy.world
        link
        fedilink
        arrow-up
        2
        ·
        11 months ago

        Exactly.

        Personally, I call it “python mode” since you’re staying on the “happy path” and let the program just crash out if those expectations aren’t met.