Go language variables


Variables come from mathematics and are abstract concepts in computer language that can store calculation results or represent values. Variables can be accessed by variable name.

Go language variable names consist of letters, numbers, and underscores, and the first letter cannot be a number.

The general form of declaring variables is to use the var keyword:

var identifier type

Variable declaration

The first method is to specify the variable type. If no value is assigned after declaration, the default value will be used.

var v_name v_type
v_name = value

The second type is to determine the variable type based on the value.

var v_name = value

The third method is to omit var. Note that the variable on the left side of := should not have been declared, otherwise it will cause a compilation error.

v_name := value

// 例如
var a int = 10
var b = 10
c : = 10

The examples are as follows:

package main
var a = "w3cschoolphp中文网"
var b string = "w3cschool.cc"
var c bool

func main(){
    println(a, b, c)
}

The execution result of the above examples is:

w3cschoolphp中文网 w3cschool.cc false

Multi-variable declaration

//类型相同多个变量, 非全局变量
var vname1, vname2, vname3 type
vname1, vname2, vname3 = v1, v2, v3

var vname1, vname2, vname3 = v1, v2, v3 //和python很像,不需要显示声明类型,自动推断

vname1, vname2, vname3 := v1, v2, v3 //出现在:=左侧的变量不应该是已经被声明过的,否则会导致编译错误


// 这种因式分解关键字的写法一般用于声明全局变量
var (
    vname1 v_type1
    vname2 v_type2
)

The examples are as follows:

package main

var x, y int
var (  // 这种因式分解关键字的写法一般用于声明全局变量
    a int
    b bool
)

var c, d int = 1, 2
var e, f = 123, "hello"

//这种不带声明格式的只能在函数体中出现
//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 are value types, and variables of these types can be used directly Points to the value stored in memory:

4.4.2_fig4.1

When using the equal sign = to assign the value of one variable to another variable, such as: j = i , actually copies the value of i in the memory:

4.4.2_fig4.2

You can use &i to get the memory address of variable i, for example: 0xf840000040 (the address may be different each time). The value of a value type variable is stored on the stack.

Memory addresses will vary depending on the machine. Even the same program will have different memory addresses after being executed on different machines. Because each machine may have a different memory layout, and the location allocation may also be different.

More complex data usually requires the use of multiple words, and these data are generally stored using reference types.

A reference type variable r1 stores the memory address (number) where the value of r1 is located, or the location of the first word in the memory address.

4.4.2_fig4.3

This memory address is called a pointer, and this pointer is actually stored in another word.

Multiple words pointed to by pointers of the same reference type can be in continuous memory addresses (the memory layout is continuous), which is also the most computationally efficient storage form; these words can also be dispersed Stored in memory, each word indicates the memory address of the next word.

When using the assignment statement r2 = r1, only the reference (address) is copied.

If the value of r1 is changed, then all references to this value will point to the modified content. In this example, r2 will also be affected.


Short form, use:= assignment operator

We know that the type of the variable can be omitted when initializing the variable and the system will automatically infer it. It actually seems a bit confusing to write the var keyword in the declaration statement. It's redundant, so we can abbreviate them as a := 50 or b := false.

The types of a and b (int and bool) will be automatically inferred by the compiler.

This is the preferred form of using variables, but it can only be used within the function body and cannot be used for declaration and assignment of global variables. Use the operator := to efficiently create a new variable, called an initialization declaration.

Note

If we cannot use an initialization statement for a variable with the same name again in the same code block, for example: a := 20 is not allowed, and the compiler will The error no new variables on left side of := is prompted, but a = 20 is OK because this is assigning a new value to the same variable.

If you use variable a before defining it, you will get the 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:

func main() {
   var a string = "abc"
   fmt.Println("hello, world")
}

Try to compile this paragraph The code will get the error a declared and not used.

Also, simply assigning a value to a is not enough, the value must be used, so using

fmt.Println("hello, world", a)

will remove the error.

But 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:

a, b, c = 5, 7, "abc"

The above line It is assumed that the variables a, b and c have all been declared, otherwise it should be used like this:

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 and the value of b is 7, and the value of c is "abc".

This is called parallel or simultaneous assignment.

If you want to swap the values ​​of two variables, you can simply use a, b = b, a.

The whitespace identifier _ is also used to discard values. For example, the value 5 is discarded in: _, b = 5, 7.

_ is actually a write-only variable, you cannot get its value. This is done because in Go you have to use all declared variables, but sometimes you don't need to use all return values ​​from a function.

Parallel assignment is also used when a function returns multiple return values. For example, val and error err here are obtained at the same time by calling the Func1 function: val, err = Func1(var1).