This is a creation in
Article, where the information may have evolved or changed.
Give me a chestnut. Global scope variable, with: = Symbol declaration Assignment new variable
" FMT " var " GG " Func Main () { n () m () N ()}func n () { fmt. Println (a)}func m () { // for: = defined variable, new variable A has the same name as global defined a variable, not at one scope // so Golong defines the new variable A. The global variable A is obscured, so m () prints the fmt of"the" "" " . Println (a)}
Local variables
Variables declared in the body of a function are called local variables, their scope is only within the function body, and the parameters and return value variables are local variables.
The main () function in the following example uses a local variable A, B, C:
Package Mainimport"FMT"Func Main () {/*declaring local variables*/ varA, B, cint /*Initialize Parameters*/a=Tenb= -C= A +FMT B. Printf ("Result: A =%d, B =%d and c =%d\n", A, B, c)}local variable declaration
Global variables
Variables declared outside the body of a function are called global variables, and global variables can be used throughout a package or even an external package (after it is exported).
Global variables can be used in any function, and the following examples demonstrate how to use global variables:
Package Mainimport"FMT"/*declaring global Variables*/varGintFunc Main () {/*declaring local variables*/ varA, bint /*Initialize Parameters*/a=Tenb= - //calling global variable declaration of GG = A +FMT B. Printf ("Result: A =%d, B =%d and g =%d\n", A, B, g)}global variable Reference
The global variable and local variable names can be the same in the Go language program, but local variables within the function are given precedence. Examples are as follows:
Package Mainimport"FMT"/*declaring global Variables*/varGint= -Func Main () {/*declaring local variables*/ varGint=TenFMT. Printf ("Result: G =%d\n", G)}//The result is G = 10, which takes precedence over local variables
Formal parameters
Formal parameters are used as local variables of the function.
Package Mainimport"FMT"/*declaring global Variables*/varAint= -; func main () {/*declaring a local variable in the main function*/ varAint=Ten varBint= - varCint=0FMT. Printf ("a =%d\n in the main () function", a); C=sum (A, b); Fmt. Printf ("C =%d\n in Main () function", c);}/*function definition-two numbers added*/func sum (A, Bint)int{fmt. Printf ("a =%d\n in the sum () function", a); Fmt. Printf ("sum () function B =%d\n", B); returnA +b;}Formal Parameters
Initializing local and global variables
The default values for the different types of local and global variables are:
| Data Type |
Initialize default values |
| Int |
0 |
| Float32 |
0 |
| Pointer |
Nil |