I need an Easy example to understand Alias This

Cym13 cpicard at purrfect.fr
Tue Jul 7 07:25:35 UTC 2020


On Tuesday, 7 July 2020 at 00:44:32 UTC, Marcone wrote:
> On Tuesday, 7 July 2020 at 00:42:40 UTC, Ali Çehreli wrote:
>> On 7/6/20 5:35 PM, Marcone wrote:
>>> Hi, I study Dlang for one year, and I can't understand alias 
>>> this. I need an Easy example to understand Alias This.
>>
>> Is the following example useful?
>>
>>   http://ddili.org/ders/d.en/alias_this.html
>>
>> Ali
>
> I can't undestand it. I need a simple example.

This only scrapes the surface, but it should give an idea of the 
core mechanics and why it's regarded as an important concept.


import std.stdio;

struct Fruit {
     string name;
}

struct ColoredFruit {
     Fruit _fruit;
     alias _fruit this;

     string color;
}

void printColoredFruit(ColoredFruit f) {
     writeln(f.color, " ", f.name);
}

void printGeneralFruit(Fruit f) {
     writeln(f.name);
}

void main(string[] args) {
     ColoredFruit banana;
     banana.color = "yellow"; // It's a normal struct for its 
non-alias members
     banana.name  = "banana"; // We can interact with internal 
fields directly

     // This function accepts a ColoredFruit so the whole banana 
is passed.
     printColoredFruit(banana);
     // > yellow banana

     // This function only doesn't accept a ColoredFruit, but it 
does accept a
     // Fruit and we have a Fruit alias this so the internal 
_fruit is passed.
     printGeneralFruit(banana);
     // > banana
}



More information about the Digitalmars-d-learn mailing list