Thank you!

Tejas notrealemail at gmail.com
Wed Sep 8 04:36:44 UTC 2021


On Tuesday, 7 September 2021 at 21:43:02 UTC, Bastiaan Veelo 
wrote:
> On Tuesday, 7 September 2021 at 13:36:39 UTC, Tejas wrote:
>>
>> ```d
>> import std.stdio;
>>
>> struct S { int i; }
>>
>> S _s;
>>
>> S s() {return _s;}
>>
>> void main()
>> {
>>     s().i = 42;
>>     writeln(_s.i == 42);
>> }
>>
>> Output:
>> false
>> ```
>>
>> Wow, compiler help much appreciated
>
> Is this confusing to you? I might be missing your point. It 
> isn’t confusing to me, `struct`s are value types. If you want 
> `s()` to return a reference to `_s` it should be declared as 
> returning a reference:
>
> ```d
> import std.stdio;
>
> struct S { int i; }
>
> S _s;
>
> ref S s() {return _s;}
>
> void main()
> {
>     s().i = 42;
>     writeln(_s.i == 42);
> }
>
> Output:
> true
> ```
>
> —Bastiaan.

The people that don't find this confusing will never even write 
`S` alone as a return type in the first place.

Again, I said that this is setting people up for frustration in 
the future, and I stick to it.

Do you really think people who are writing code like that expect 
a temporary to be generated? What else could be the purpose of 
returning an existing struct and using it as an `lvalue` if not 
to modify it?

I feel we would be better off if the same
```d
<your_var_name> is not an lvalue and cannot be modified
```

error that is raised for other similar cases came up in the 
original version of this code. It will catch a (almost 100% 
guranteed) runtime error during compile time _and_ be consistent 
with the rest of the language.


More information about the Digitalmars-d mailing list