Go has four main types of declarations: var, const, type, and func, which correspond to declarations of variables, constants, types, and function entity objects, respectively.

  1. Source files with a. Go suffix start with a package declaration statement, indicating which package the source file belongs to.
  2. The package declaration statement is followed by the import statement that imports the other packages that depend on.
  3. This is followed by package-level declarations of types, variables, constants, and functions.

A name that declares a statement at the package level can be accessed in every source file that corresponds to the entire package, not just in the source file where the statement is declared. Locally declared names, by contrast, can only be accessed within a narrow range of functions.

Variable declarations

The var declaration statement creates a variable of a particular type, appends it to a name, and sets its initial value. The general syntax of variable declaration is as follows: var Variable name Type = expression You can omit either type or = expression. If type information is omitted, the type information of the variable is derived from the initialization expression. If the initialization expression is omitted, the variable is initialized with a zero value.

You can also declare a set of variables together in a declaration statement, or declare and initialize a set of variables with a set of initialization expressions. If you omit the type of each variable, you can declare multiple variables of different types (the types are derived from the initialization expression).

The initialization expression can be literal or arbitrary. Variables declared at the package level are initialized before the main entry function is executed, and local variables are initialized when the declaration statement is executed.

Short variable declaration

Inside functions, a form called a short variable declaration statement can be used to declare and initialize local variables. Name := The type of the expression variable is automatically derived from the expression

The variables to the left of the short variable declaration may not all be newly declared. If there are already declared variables in the same locale, the short variable declaration statement only has assignment behavior for those already declared variables, and it must declare at least one new variable.