Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `type` keyword actually means when used in a type definition? [duplicate]

I've recently read some lines of the VCL source code and found the definition of the TCaption type:

TCaption = type string;

I've always thought it was just another name for string type and I was thinking that it was defined as follows:

TCaption = string;

So, I've looked for documentation about the type keyword and I've found this:

  1. type Name = Existing type
    Refers to an existing type, such as string by a new Name.

  2. type Name = type Existing type
    This has the same effect as above, but ensures that at run time, variables of this type are identified by their new type name, rather than the existing type name.

After reading it, I'm still confused and I don't understand what "...ensures that at run time, variables of this type are identified by their new type name..." actually means.

Could someone shed some light on this?

like image 579
Fabrizio Avatar asked Aug 19 '17 16:08

Fabrizio


People also ask

What is type keyword?

Type Keyword. The type keyword defines an alias to a type. type str = string; let cheese: str = 'gorgonzola'; let cake: str = 10; // Type 'number' is not assignable to type 'string'

What is type keyword in go?

The type keyword is there to create a new type. This is called type definition. The new type (in your case, Vertex) will have the same structure as the underlying type (the struct with X and Y). That line is basically saying "create a type called Vertex based on a struct of X int and Y int".


1 Answers

Consider the following code, and note that the procedure Check() has a var parameter:

type
  Ta = string;       // type alias
  Tb = type string;  // compatible but distinct new type

procedure Check(var s: string);
begin
  ShowMessage(s);
end;

procedure TMain.Button2Click(Sender: TObject);
var
  a: Ta;
  b: Tb;
begin
  a := 'string of type Ta,';
  b := 'string of type Tb.';
  Check(a);
  Check(b);
end;

Check(b) results in a compiler error: E2033 Types of actual and formal var parameters must be identical

In the above, type Tb is compatible with string in that you can f. ex. assign a := b, but it is distinct in that the type identifier (under the hood) has a different value, and therefore not accepted as argument for Check(var s: string).

like image 104
Tom Brunberg Avatar answered Oct 12 '22 22:10

Tom Brunberg