Variable Scope in Go
Scope is the range in source code within which a constant, type, variable, function, or package represented by a declared identifier is applicable.
In Go, variables can be declared in three places:
- Variables defined inside a function are called local variables
- Variables defined outside a function are called global variables
- Variables in a function definition are called formal parameters
Next, let's take a closer look at local variables, global variables, and formal parameters.
local variables
Variables declared inside a function body are called local variables; their scope is limited to the function body, and parameter and return value variables are also local variables.
In the following example, the main() function uses local variables a, b, c:
Example
package
main
import
"fmt"
func
main
()
{
/* Declare local variables */
var
a
,
b
,
c
int
/* initialize parameters */
a
=
10
b
=
20
c
=
a
b
fmt
.
Printf
(
"result: a = %d, b = %d and c = %d\n"
,
a
,
b
,
c
)
}
The output of the above example is:
结果: a = 10, b = 20 and c = 30
Global Variables
Variables declared outside a function body are called global variables; global variables can be used throughout the package and even in external packages (after being exported).
Global variables can be used in any function; the following example demonstrates how to use global variables:
Example
package
main
import
"fmt"
/* declare global variables */
var
g
int
func
main
()
{
/* Declare local variables */
var
a
,
b
int
/* initialize parameters */
a
=
10
b
=
20
g
=
a
b
fmt
.
Printf
(
"result: a = %d, b = %d and g = %d\n"
,
a
,
b
,
g
)
}
The output of the above example is:
结果: a = 10, b = 20 and g = 30
In a Go program, global and local variables can have the same name, but the local variable inside the function takes precedence. Example as follows:
Example
package
main
import
"fmt"
/* declare global variables */
var
g
int
=
20
func
main
()
{
/* Declare local variables */
var
g
int
=
10
fmt
.
Printf
(
"result: g = %d\n"
,
g
)
}
The output of the above example is:
结果: g = 10
formal parameters
Formal parameters are used as local variables of the function. Example as follows:
Example
package
main
import
"fmt"
/* declare global variables */
var
a
int
=
20
;
func
main
()
{
/* declare local variables in the main function */
var
a
int
=
10
var
b
int
=
20
var
c
int
=
0
fmt
.
Printf
(
"in main() function a = %d\n"
,
a
);
c
=
sum
(
a
,
b
);
fmt
.
Printf
(
"in main() function c = %d\n"
,
c
);
}
/* function definition - add two numbers */
func
sum
(
a
,
b
int
)
int
{
fmt
.
Printf
(
"in sum() function a = %d\n"
,
a
);
fmt
.
Printf
(
"in sum() function b = %d\n"
,
b
);
return
a
b
;
}
The output of the above example is:
main()函数中 a = 10
sum() 函数中 a = 10
sum() 函数中 b = 20
main()函数中 c = 30
Initializing local and global variables
The default values of local and global variables of different types are:
| Data Type | Default Initialization Values |
|---|---|
| int | 0 |
| float32 | 0 |
| pointer | nil |