go local variables and global variables

Go uses the const keyword to define constants and the var keyword to define variables. How it is defined: var {key} {type}
defines a single object:
var str string = "hello"

Define multiple uniform types:
var p, q float32 = 1.1, 2.2

or:
where (
	k = 1
	t = 2
)

Note: string and float32 can be removed, the compiler will automatically determine.

After a variable is defined, it can be used in a certain scope in the program. We become the scope. According to the size of the scope, we can divide it into global variables and local variables. Variables declared outside a function are called global variables and can be used freely within a function. The object declared in the function, the scope is only in this function, we call it a local variable, let's take an example to illustrate:
package main

var a = "G"

where (
	k = 1
	t = 2
)

var p, q float32 = 1.1, 2.2

func main() {
	var a string
	a = "t"
	b := "q"
	n()
	m()
	n()
	print("main :\n")
	print(a, b, q, p)
}

func n() {
	print(a)
}

func m () {
	a = "O"
	print(a)
}

In the above example: a , k, t, p, q are global variables, declared outside the function
In the main function, a, b are local variables.
Note: : a is both a local variable and a global variable.
:= is also an assignment method, omitting the keyword var will automatically determine the variable type.
Analysis: The function starts to execute from the main method, the method body
The first line: define a as a string type variable
Second line: assign the string t to a
Third line: define b as the string type and assign the string q to it.
Fourth line: Execute n function, output a, this a takes the global variable, so output G
Fifth line: execute m function, first turn global variable a into O, so output O
Line six: execute n function, because a It becomes O in the m function, so n outputs O
The eighth line: outputs the values ​​of a, b, q, p, where a takes the local variable a, so it is t.
Note that if var a string is commented out, a = "t" will modify the global variable, so the result will be completely different.

Conclusion: If the global variable is redefined in the function, the value of the global variable will be hidden in the function.
If a global variable is defined and not referenced, an error will not be reported. If
a local variable is defined and not referenced, an error will be reported: declared and not used

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326919302&siteId=291194637