This is a creation in Article, where the information may have evolved or changed.
PackageMainImport "FMT"funcMain () {//Program EntryInitvariable () assignmentvariable () anonymousvariable ()}/* Variable declaration func declarevariable () {//Go language variables are declared differently from the C and C + + languages. For a purely variable declaration, the Go language introduces the//keyword VAR, and the type information is placed after the variable name, as shown in the following example: VAR v1 int var v2 string var v3 [10]int//array var v4 []in t//array tile var v5 struct {f int} var v6 *int//pointer var v7 map[string]int//Map,key to String type, value in The T-type Var v8 func (a int) int//Variable declaration statement does not need to use a semicolon as a terminator. In contrast to the C language, the go language abandons the habit of having to use a semicolon for a statement to end a tag. Another use of the VAR keyword is that you can put several variables that need to be declared together, lest the programmer need to repeat//write the var keyword as follows: var (v11 int v22 string)//Note : variable declaration must be used, or compile error: "XX declared and not used"}*// * Initialization statement for variable * /funcInitvariable () {fmt. Println ("-------Variable initialization--------")//Mode 1: Declare variables and types, declare a set of variables by () var(xintYint) x =3y =4Fmt. Printf ("X=%v, y=%v\n", X, y)//Mode 2: Declare variable, variable type, and initialize varIint=1 varJint=2Fmt. Println (I+J)//Mode 3: Declare the variable and initialize it, and the type of the variable is automatically deduced by the compiler varK =1 varm =2Fmt. Println ("K + M =", k+m)//Mode 4: Declare the variable and initialize it, the specified type is no longer required, the variable that appears on the left side should not have been declared, otherwise it will cause a compilation erroro: =1P: =2Fmt. PRINTLN (O * p)}/ * Assignment of variables * /funcAssignmentvariable () {fmt. Println ("Assignment of-------variable--------")//In Go syntax, variable initialization and variable assignment are two different concepts //general assignment varVintv = -Fmt. Println ("v=", V)//go language supports multiple assignments, reducing the use of intermediate variablesI: =1J: =2Fmt. Printf ("i=%v,j=%v\n before Exchange", I, J) I, j = j, I fmt. Printf ("i=%v,j=%v\n after Exchange", I, J)}/ * Anonymous variable * /funcAnonymousvariable () {fmt. Println ("-------anonymous variable--------") _,_, LastName: = GetName ()//go The use of multiple return values for a language support function, if you do not want to receive a return value you can use _ to representFmt. Println ("Lastname=", LastName)}funcGetName () (Firstname,middlename,lastnamestring){return "Chen","You","Sheng"}
Operation Result: