Any way to automatically convert structs on return?

Lance Bachmeier no at spam.net
Thu Aug 1 13:07:09 UTC 2024


On Thursday, 1 August 2024 at 07:25:53 UTC, Emma wrote:

> but this doesn't:
>
> ```d
> Option!int something() {
>   return None(); // Error: cannot implicitly convert expression 
> `None()` of type `None` to `Option!int`
> }
> ```

For the program you've written, I'm happy it doesn't compile, 
because a lot of the time the compiler would be making buggy code 
compile - though I would love to have a way to do it explicitly. 
In this case you can change your definition of None to use alias 
this and it will compile:

```
struct None {
     alias convert this;

     Option!int convert() {
         return Option!int(None());
     }
}
```


More information about the Digitalmars-d-learn mailing list