How does alias exactly work

Paul Backus snarwin at gmail.com
Tue Sep 29 03:16:36 UTC 2020


On Tuesday, 29 September 2020 at 01:46:56 UTC, Ruby The Roobster 
wrote:
> I thought alias could work like this with classes:
>
> alias test = MyClass(3,"H",9.1); //Assume the constructor 
> parameters for MyClass are (int,string,double).
>
> Can anybody fix this code?

`alias` lets you create a new name for an entity that already 
exists somewhere in your program.

The "entity" in question can be a lot of different things--a 
type, a variable, a function, a module, a template--but it must 
be something that exists independently of the alias. In other 
words, you cannot use `alias` to give a name to something that 
does not already have one.

But wait, you might ask, if that's true, how can you alias a 
lambda? It's an anonymous function; by definition, it doesn't 
have a name!

     alias increment = (int x) => x + 1;

The thing is...lambdas actually do have names. They're just 
generated internally by the compiler. You can't actually *use* 
them in your code, but they do occasionally show up in error 
messages:

     increment("hello");
     // Error: function literal `__lambda1(int x)` is not callable 
using argument types `(string)`




More information about the Digitalmars-d-learn mailing list