Don’t say anyway, say anyhow

      • magic_lobster_party@fedia.io
        link
        fedilink
        arrow-up
        29
        ·
        20 days 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”

      • Ediacarium@feddit.org
        link
        fedilink
        arrow-up
        11
        ·
        20 days ago

        Languages like Java or C++ have Exceptions, which are errors, that are not explicitly mentioned in the function signature. Meaning, you might need to handle an exception you didn’t even know existed. And if you don’t, your program will just crash when these exceptions occur.

        In Rust all errors are explicitly mentioned and part of the return type. Because of this Rust has a lot of ways to quickly handle an error. One of those ways is “Trust me, bro” (or .unwrap()), which converts the combined error/success return type into just a success type, causing the program to crash if it actually was an error, restoring the more unsafe behavior of other languages.

        • thevoidzero@lemmy.world
          link
          fedilink
          arrow-up
          3
          ·
          20 days ago

          Crashing through unwrap is not necessarily restoring unsafe behavior of other languages though. I’d consider this wayyyy better than silently continuing with invalid value until the program tries something that doesn’t make sense/is overreaching and it crashes.