DIP1000: Walter's proposal to resolve ambiguity of ref-return-scope parameters

Paul Backus snarwin at gmail.com
Sat Nov 27 03:41:05 UTC 2021


On Saturday, 27 November 2021 at 01:17:15 UTC, zjh wrote:
> On Friday, 26 November 2021 at 14:48:21 UTC, Paul Backus wrote:
>
>>> ```d
>>> inout int[] getSomething(inout return this, int offset) 
>>> @property { ... }
>>> ```
>
> Why copy `rust`.

Actually, I got the idea from Python. :)

Why do I think it's a good idea? Because it makes it really 
obvious which attributes apply to `this` and which attributes 
apply to the function as a whole.

For example, here's a really common error that beginning D 
programmers make:

```d
struct S
{
     private int[] a;
     const int[] getArray() const { return a; }
}
```

If you try to compile this code, you get the following error:

```
Error: redundant attribute `const`
```

The reason for this is that in the above code, *both* instances 
of `const` are treated as applying to the `this` reference, not 
to the return value. The fix is to add `()` to the first `const`:

```d
     const(int[]) getArray() const { return a; }
```

With an explicit `this` parameter, there is no room for ambiguity:

```d
     const int[] getArray(const ref this) { return a; }
```

The outer `const` can only apply to the return value, and the 
inner `const` can only apply to the `this` reference.


More information about the Digitalmars-d mailing list