Don’t say anyway, say anyhow

      • magic_lobster_party@fedia.io
        link
        fedilink
        arrow-up
        34
        ·
        1 day 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
        12
        ·
        1 day 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.

        • Dave.@aussie.zone
          link
          fedilink
          arrow-up
          6
          ·
          1 day ago

          causing the program to crash if it actually was an error, restoring the more unsafe behavior of other languages.

          Wellllll it’s more of an abrupt exit rather than a crash, which is still better than eg. silently accessing beyond the end of an array, or ending up with a pointer to nowhere when you thought you had a sane memory reference.

          • arendjr@programming.dev
            link
            fedilink
            arrow-up
            4
            arrow-down
            1
            ·
            1 day ago

            “An abrupt exit”, more commonly known as a “crash”.

            If you’re going to argue that an exit through panic!() is not a crash, I will argue that your definition of a crash is just an abrupt exit initiated by the OS. In other words, there’s no meaningful distinction as the result is the same.

            • Dave.@aussie.zone
              link
              fedilink
              arrow-up
              1
              ·
              edit-2
              11 hours ago

              I was talking more about unwrap causing a panic rather than calling the actual panic macro directly. Rust forces the programmer to deal with bad or ambiguous results, and what that is exactly is entirely decided by the function you are calling. If a function decides to return None when (system timer mod 2 == 0), then you’d better check for None in your code. Edit: otherwise your code is ending now with a panic, as opposed to your code merrily trotting down the path of undefined behaviour and a segfault or similar later on.

              Once you get to a point where we are doing the actual panic, well, that is starting to just be semantics.

            • qaz@lemmy.worldOP
              link
              fedilink
              English
              arrow-up
              5
              ·
              edit-2
              1 day ago

              I don’t think that’s a valid comparison. The behavior does differ when it comes to cleanly releasing resources. Rust’s panic performs the drop actions for the current values on the stack, a SIGILL or SIGSEGV crash doesn’t.

              #[derive(Debug)]
              struct MyStruct {}
              
              impl Drop for MyStruct {
              	fn drop(&mut self) {
              		println!("{:?}", "imagine cleanup here"); // this is called
              	}
              }
              
              fn main() {
              	let a = MyStruct {};
              	panic!("panic!");
                      println!("{a:?}");
              }
              

              Try it yourself

              • arendjr@programming.dev
                link
                fedilink
                arrow-up
                6
                ·
                1 day ago

                That’s fair, although technically you could catch SIGSEGV and release resources that way too.

                Also, given that resources will be reclaimed by the OS regardless of which kind of crash we’re talking about, the effective difference is usually (but not always) negligible.

                Either way, no user would consider a panic!() to be not a crash because destructors ran. And most developers don’t either.

        • thevoidzero@lemmy.world
          link
          fedilink
          arrow-up
          3
          ·
          1 day 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.

  • magic_lobster_party@fedia.io
    link
    fedilink
    arrow-up
    19
    ·
    1 day ago

    I prefer it over alternatives:

    • Exceptions: ”Oh no! Guess I’ll just die”
    • Error codes: ”If a non-zero error code is returned but no one notices, is it really an error?”
    • fayoh@sopuli.xyz
      link
      fedilink
      arrow-up
      6
      ·
      1 day ago

      The crash early, crash often approach of Erlang has made for some amazingly resilient systems.

      One time on a project I was working on, some horribly broken code was merged (nobody in the team had even heard of reviewing code). As soon as a specific call was made, it was executed once and then the thread crashed. The only way we noticed was that response times increased with load. All data and behavior was still correct. Whole nodes could go down and all you notice is a dip in performance until it comes back online.

      Of course it requires special care in designing. Everything runs in stateless server threads with supervisors restarting them as needed. This in turn requires some language support, like lightweight threads. Our application would happily run tens of thousands of threads on an ancient sparkstation.

    • r00ty@kbin.life
      link
      fedilink
      arrow-up
      5
      ·
      1 day ago

      It is a nicer way I think. But other languages do allow for good exception handling. It’s just there’s not a clear cut sign that no-one has handled the exception yet. So often it doesn’t get handled.

      What I mean by that is. If I have a function that returns say a string. As a caller, you don’t know whether that function is always going to return a string (it handled exceptions internally), or if it returns a string but might return an exception. So you need to try/catch (or whatever is the equivalent in that language). It’s not clear to the caller.

      Whereas with rust, if you’re holding a value wrapped in a result, it means that any exception hasn’t been handled yet. If you’re not passing the value (still inside the result) back to a caller, tag you’re it! :P

      • magic_lobster_party@fedia.io
        link
        fedilink
        arrow-up
        8
        ·
        1 day ago

        I like the flexibility Rust offers with the result type. It makes the error handling part of the control flow rather than an afterthought.