Variables come from mathematics. They are abstract concepts that can store calculation results or represent values in computer language.
Variables can be accessed by variable names.
The Go language variable name consists of letters, numbers and underscores, and the first character cannot be a number.
The general form of declaring variables is to use the var keyword:
var identifier type
You can declare multiple variables at once:
var identifier1, identifier2 type
example
package main import "fmt" func main() { var a string = "Runoob" fmt.Println(a) var b, c int = 1, 2 fmt.Println(b, c) }
The output results of the above examples are:
Runoob 1 2
Variable declaration
First, specify the variable type. If it is not initialized, the variable defaults to zero.
var v_name v_type v_name = value
The value of zero is the value set by the system by default when the variable is not initialized.
example
package main import "fmt" func main() { // Declare a variable and initialize it var a = "RUNOOB" fmt.Println(a) // Zero value without initialization var b int fmt.Println(b) // bool zero value is false var c bool fmt.Println(c) }
The execution result of the above example is:
RUNOOB 0 false
- The value type (including complex64/128) is 0
- Boolean type is false
- String is' '(empty string)
- The following types are nil:
var a *int var a []int var a map[string] int var a chan int var a func(string) int var a error // error is the interface
example
package main import "fmt" func main() { var i int var f float64 var b bool var s string fmt.Printf("%v %v %v %q\n", i, f, b, s) }
The output is:
0 0 false ""
The second is to determine the type of variable according to the value.
var v_name = value
example
package main import "fmt" func main() { var d = true fmt.Println(d) }
The output is:
true
Third, omit var. note: = if no new variable is declared on the left, a compilation error will be generated. Format:
v_name := value
For example:
var intVal int intVal :=1 // At this time, a compilation error will occur because intVal has been declared and does not need to be declared again
Use the following statement directly:
intVal := 1 // At this time, there will be no compilation error because a new variable is declared, because: = is a declaration statement
Intval: = 1 equals:
var intVal int intVal =1
var f string = "Runoob" can be abbreviated as F: = "Runoob":
example
package main import "fmt" func main() { f := "Runoob" // var f string = "Runoob" fmt.Println(f) }
The output is:
Runoob
Multivariable declaration
//Multiple variables of the same type, non global variables var vname1, vname2, vname3 type vname1, vname2, vname3 = v1, v2, v3 var vname1, vname2, vname3 = v1, v2, v3 // Much like python, it does not need to display the declaration type and is automatically inferred vname1, vname2, vname3 := v1, v2, v3 // Variables appearing on the left side of: = should not have been declared, otherwise compilation errors will be caused // This factorization keyword is generally used to declare global variables var ( vname1 v_type1 vname2 v_type2 )
example
package main var x, y int var ( // This factorization keyword is generally used to declare global variables a int b bool ) var c, d int = 1, 2 var e, f = 123, "hello" //This kind of without declaration format can only appear in the function body //g, h := 123, "hello" func main(){ g, h := 123, "hello" println(x, y, a, b, c, d, e, f, g, h) }
The execution result of the above example is:
0 0 0 false 1 2 123 hello 123 hello
Value type and reference type
All basic types such as int, float, bool and string belong to value types. Variables using these types directly point to values stored in memory:
When the equal sign = is used to assign the value of one variable to another variable, such as j = i, the value of i is actually copied in memory:
You can use & i to get the memory address of variable i, for example: 0xf840000040 (the address may be different every time). The value of variable of value type is stored in the stack.
The memory address will vary according to different machines. Even after the same program is executed on different machines, it will have different memory addresses. Because each machine may have a different memory layout, and the location allocation may be different.
More complex data usually needs to use multiple words, and these data are generally saved with reference types.
A reference type variable r1 stores the memory address (number) where the value of r1 is located, or the position of the first word in the memory address.
This memory address is called a pointer, which is actually stored in another value.
Multiple words pointed to by the pointer of the same reference type can be in continuous memory addresses (memory layout is continuous), which is also a storage form with the highest computational efficiency; these words can also be stored in memory separately, and each word indicates the memory address of the next word.
When the assignment statement r2 = r1 is used, only the reference (address) is copied.
If the value of r1 is changed, all references to this value will point to the modified content. In this example, r2 will also be affected.
Short form, using: = assignment operator
We know that the type of variable can be omitted during variable initialization and automatically inferred by the system. It is redundant to write the var keyword in the declaration statement, so we can abbreviate them as a: = 50 or B: = false.
The types of a and b (int and bool) are automatically inferred by the compiler.
This is the preferred form of using variables, but it can only be used in function bodies, not in the declaration and assignment of global variables. Using the operator: =, you can efficiently create a new variable called an initialization declaration.
matters needing attention
In the same code block, we can't use initialization declarations for variables with the same name again. For example, a: = 20 is not allowed, and the compiler will prompt the error no new variables on left side of: =, but a = 20 is OK, because it gives a new value to the same variable.
If you use variable a before defining it, you will get a compilation error undefined: a.
If you declare a local variable but do not use it in the same code block, you will also get a compilation error, such as variable a in the following example:
example
package main import "fmt" func main() { var a string = "abc" fmt.Println("hello, world") }
Trying to compile this code will get an error a declared and not used.
In addition, simply assigning a value to a is not enough. This value must be used, so it is used
fmt.Println("hello, world", a)
The error is removed.
However, global variables are allowed to be declared but not used. Multiple variables of the same type can be declared on the same line, such as:
var a, b, c int
Multiple variables can be assigned on the same line, such as:
var a, b int var c string a, b, c = 5, 7, "abc"
The above line assumes that variables a, b and c have been declared. Otherwise, it should be used as follows:
a, b, c := 5, 7, "abc"
The values on the right are assigned to the variables on the left in the same order, so the value of a is 5, the value of b is 7, and the value of c is "abc".
This is called parallel or simultaneous assignment.
If you want to exchange the values of two variables, you can simply use a, b = b, a. the types of the two variables must be the same.
Blank identifier_ It is also used to discard values, such as value 5 in:, B = abandoned in 5, 7.
_ It's actually a write only variable. You can't get its value. This is because you have to use all declared variables in the Go language, but sometimes you don't need to use all the return values from a function.
Parallel assignment is also used when a function returns multiple return values. For example, val and error err are obtained simultaneously by calling Func1 function: val, err = Func1(var1).