This is a creation in Article, where the information may have evolved or changed.
1. Variables
1.1 Declaring variables
Use the var keyword to create a variable of the specified type:
int = 0= 0int
The above three expressions are valid, the third expression initializes I to 0 values of type int, 0 if I is a bool type, or false;i is a float64 type, or 0.0;i is a string type, or ""; I is a interface type, or nil ; I is a reference type, or nil; if I is a struct, it is initialized to a 0 value of the corresponding type for all fields in the struct.
You can declare multiple variables in the same statement:
int // int, int, int true // bool, float64, String
Variables that are visible within the package are initialized before the main function begins execution, and local variables are initialized when the function executes to the corresponding declaration statement.
Variables can also be initialized by the function's return value:
// OS. Open returns a file and an error
1.2 Short statement
Inside the function, there is a short declaration, in the form of name: = Expression, where the type of the variable is automatically determined by the compiler.
ANIM: = gif. Gif{loopcount:nframes}freq:= rand. Float64 () * 3.0t:= 0.0
Because this form is very concise, it is used extensively inside the function (local variables). If you need to explicitly specify a type for a local variable, or if you want to declare a variable followed by a value , you should use var:
1 I: = +/ /an int2// a float643var names [] String4var err error5 var p point
Like the Var declaration, a short declaration can also be initialized in parallel
I, J: = 0, 1
Keep in mind that: = is a declaration, = is an assignment, and therefore cannot be used where the value is to be assigned: =
1 int 2 I: = ten//panic:no New variables on left side of: =
you can use the attributes of the parallel assignment to Value Exchange :
1 // swap values of I and J
One thing to note: The variable on the left of the short declaration is not necessarily the new declaration!
1 // New Declaration Two variables: in, err 2 // ... 3 out, err: = os. Create (path2) 4/*5 although used here: =, but err is declared in the last statement, here is only the assignment */
Also, the left variable of the short declaration must have a new one, and if it was previously declared, a compilation error is reported:
1 F, err: = os. Open (infile) 2/ /... 3 //
The correct wording is this:
1 F, err: = os. Open (infile) 2/ /... 3 // Compile OK
1.3 Hands
- f, err := os. Open (infile)
- //&NBSP, .....   
- f, err = os. Create (outfile) // compile ok