File variables in the previous chapter, we have repeated the name of the type on both sides of the
File file = File("student_records", "w");
It feels redundant. It would also be cumbersome and especially error-prone if the type name were longer:
VeryLongTypeName var = VeryLongTypeName(/* ... */);
Fortunately, the type name on the left-hand side is not necessary because the compiler can infer the type of the left-hand side from the expression on the right-hand side. For the compiler to infer the type, the
auto keyword can be used:
auto var = VeryLongTypeName(/* ... */);
auto can be used with any type even when the type is not spelled out on the right-hand side:
auto duration = 42; auto distance = 1.2; auto greeting = "Hello"; auto vehicle = BeautifulBicycle("blue");
Although "auto" is the abbreviation of automatic, it does not come from automatic type inference. It comes from automatic storage class, which is a concept about the life times of variables.
auto is used when no other specifier is appropriate. For example, the following definition does not use
immutable i = 42;
The compiler infers the type of
immutable int above. (We will see
immutable in a later chapter.)
typeof provides the type of an expression (including single variables, objects, literals, etc.) without actually evaluating that expression.
The following is an example of how
typeof can be used to specify a type without explicitly spelling it out:
int value = 100; // already defined as 'int' typeof(value) value2; // means "type of value" typeof(100) value3; // means "type of literal 100"
The last two variable definitions above are equivalent to the following:
int value2; int value3;
It is obvious that
typeof is not needed in situations like above when the actual types are known. Instead, you would typically use it in more elaborate scenarios, where you want the type of your variables to be consistent with some other piece of code whose type can vary. This keyword is especially useful in templates and mixins, both of which will be covered in later chapters.
As we have seen above, the type of literals like 100 is
int (as opposed to
long, or any other type). Write a program to determine the type of floating point literals like 1.2.
.stringof would be useful in this program.