Possibility of adopting Rust's Error Handling?

mesni mensikovk817 at gmail.com
Sat Apr 2 02:54:47 UTC 2022


On Thursday, 31 March 2022 at 21:21:04 UTC, mee6 wrote:
> Rust's error handling is pretty good, I think they've proved 
> the use of Result!(T, E). I was just always getting informative 
> messages from the get go. I think there's a @nogc exception DIP 
> in the works but I think this way of handling errors is better.
>
> I won't go too much into detail of rust as this website does a 
> good job of going over it.
>
> https://doc.rust-lang.org/book/ch09-00-error-handling.html
>
> Anyways this could be adopted instead of trying to get @nogc 
> exceptions working. Rust uses exceptions but only for panic!() 
> Which terminates the application. All it does is rewind the 
> stack to see all the function calls for debugging pretty much.
>
> I also think it works with chaining functions as that's what 
> Rust does a lot too. They have a `?` operator that does 
> basically this boiler plate code.
>
> ```d
> auto result = expr;
> if (result.isErr())
>     return result;
> ```
>
> D could implement this fairly easily and without much 
> intrusion, but it would add a lot of value to be able to do 
> something like:
>
> ```rust
> auto value = chain()?.funcs()?;
> ```
>
> While being @nogc and without using exceptions. Other than for 
> panics.

Moreover, here is an interesting trick

```d
import std.stdio;
import std.typecons;
import std.exception;

     template ErrorGet(alias Func){
         ref auto getn(T)(ref T n){
             if(n.isNull) Func(0);
             return n.get();
         }
     }

alias PanicGet = ErrorGet!((a){assert(a);});
alias ThrowGet = ErrorGet!(enforce);

     void main(){
         Nullable!int a;
         a = 8;
         with(PanicGet){
            	a.getn.writeln;
         }
         with(ThrowGet){
             a.getn.writeln;
         }
      }
      ```


More information about the Digitalmars-d mailing list