Question mark operator proposals

Dadoum dadoum at protonmail.com
Fri May 12 13:02:25 UTC 2023


There were at some point discussions in the forum about error 
handling and adding a potential question mark operator in D, and 
I would support it personally since it would allow to force 
caller of a function to handle some recoverable errors which can 
happen frequently (especially with `@mustuse`).

With current sumtypes, we can already do some cool stuff, and I 
am already using them for that, but I think that a question mark 
operator (or any other symbol if it conflicts with ternary 
syntax) as Rust does would be a nice addition to allow more 
flexibility and readability. To make things simple, maybe opUnary 
can be reused as such (or not, maybe the rewrite happens earlier, 
then opQuestion should do the job I guess):

```d
struct ServerError {
     int error;
     string message;
}
alias ServerResponse = SumType!(string, ServerError);

bool opUnary(string op = "?")(ServerResponse response, out string 
content, out ServerError error) {
     return response.match!(
             (string res) => (content = res, true),
             (ServerResponse err) => (error = err, false),
     );
}
```

Otherwise, a special function could also work (but currently 
there is no way to make this kind of a macro-like functions in a 
D library, and I can't think of any syntax that could allow this 
in a clean way) which would look more integrated to D than 
question mark.

```d
// Passing error handling a potential UI layer

// with question mark.
Account account = AuthServer.authenticate(mail, password)?;
// with a function.
Account account = AuthServer.authenticate(mail, 
password).propagate;
// maybe a bit long? `handle` is vague, and abbreviations would 
probably make the code unclear.
```


More information about the Digitalmars-d mailing list