Thread overview | |||||
---|---|---|---|---|---|
|
May 18, 2017 alias this and struct initializer | ||||
---|---|---|---|---|
| ||||
Hi, I have some issues with struct initializer and alias this. In following example 1 and 2 is working but there is a syntax error for 3. I think as case 2 is working case 3 should work also. For me case 3 is looking much nicer than case 1. What do you think? void main() { // Working Request request1 = { definitions: {[ Definition("A", "B") ]} }; // Working Request request2; request2.definitions = [Definition()]; // cannot implicitly convert expression ([Definition("A", "B")]) of type Definition[] to Definitions Request request3 = { definitions: [ Definition("A", "B") ] }; } struct Request { Definitions definitions; } struct Definitions { private Definition[] _arr; alias values this; @property Definition[] values(){return _arr;} @property void values(Definition[] values){_arr = values;} } struct Definition { string attributeName; string attributeType; } Kind regards André |
May 18, 2017 Re: alias this and struct initializer | ||||
---|---|---|---|---|
| ||||
Posted in reply to Andre Pany | On Thursday, 18 May 2017 at 08:40:39 UTC, Andre Pany wrote:
> I think as case 2 is working case 3 should work also.
Nope, case 2 is assigning to an already constructed object and case 3 is constructing a new one.
alias this is NEVER used in construction. It can only apply after the object already exists, just like subclasses vs interfaces. Once the object exists, you can assign a subclass to an interface, but you can't do
SubClass obj = new Interface();
in theory, the compiler could see the left hand side and know it is supposed to be SubClass, but it doesn't - you need to construct the class explicitly.
Same with alias this, it allows implicit conversion TO the type and assignment of the member through the existing variable (the existing variable must already be valid, it is already constructed, so it is no different than assigning any other public member), but not implicit conversion FROM the type since the new struct may have other members that need to be initialized too.
|
May 18, 2017 Re: alias this and struct initializer | ||||
---|---|---|---|---|
| ||||
Posted in reply to Adam D. Ruppe | On Thursday, 18 May 2017 at 12:56:09 UTC, Adam D. Ruppe wrote:
> On Thursday, 18 May 2017 at 08:40:39 UTC, Andre Pany wrote:
>> [...]
>
> Nope, case 2 is assigning to an already constructed object and case 3 is constructing a new one.
>
> [...]
Thanks for the explanation, that makes perfectly sense.
Kind regards
André
|
Copyright © 1999-2021 by the D Language Foundation