Variable declaration style

Starting from C, a strongly typed style is used , and type modifiers are used when declaring variables. For different data types, different modifiers need to be used.

Take Java as an example

char c = 'c';
int num = 10;
boolean ok = true;

However, there is another style, which is to use a keyword to declare the variable regardless of its type, such as var1 (variable abbreviation):

// 要是不做说明,或许还以为这是 JS 呢,实则为 Java
var s = "str";
var num = 10;
var ok = false;

The advantage of this is that the type of the variable is inferred by the compiler itself. In most cases, this is more accurate than the developer's own explicit annotation.

C does not provide this type of play; a similar one exists in C++ auto2 .

In the long-term development, some strongly typed languages ​​also support this method, but it is not used much because there is a problem: language programming style . Especially in languages ​​that have type declaration methods, it is easy to mix things up and make your code style confusing.

In most cases, only for complex and long type declarations, developers will choose to use varto simplify the declaration by default.

Secondly, as a habit, explicitly type-declaring variables can make people feel more secure, and when you see the area where the variable is declared, you will know what type the variable is.

varMoreover, from the beginning of learning the language, we will use the strong type declaration method (I don't believe which Java tutorial will let people use variable declaration from the beginning ), so I am accustomed to this traditional method.

Of course, it can be said that the latter unified style of writing is a writing method that most developers are willing to accept (at least I am). After all, it is easier to remember a declaration keyword than a bunch of type keywords.

So a solution emerged: coexistence .

Use a keyword to declare a variable, and at the same time, provide a type annotation method to selectively write the variable type, and also allow the editor to perform automatic inference. Currently known languages ​​of this style include: TypeScript, Rust, Python

Python only demonstrates type annotations here

const str = "str";
const num: number = 10;
let str = "str";
let num: i32 = 10;
s: str = "abc"  
num: int = 10  
ok: bool = False

Type annotations also show that strong typing is a very popular feature. This conclusion can also be drawn from TypeScript, so that a new proposal has emerged to add type annotation functions to JavaScript.

-END-


  1. Known available languages ​​are: JS, Java, C#. ↩︎

  2. Its scope of application is varwider than that of . ↩︎

Guess you like

Origin blog.csdn.net/qq_49661519/article/details/125964559