mirror of
https://gitee.com/shikong-sk/golang-study
synced 2025-02-23 07:22:16 +08:00
docs: Scope 变量作用域
This commit is contained in:
parent
16a819821e
commit
da6f7409b0
27
base/scope/main.go
Normal file
27
base/scope/main.go
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// 定义 全局变量
|
||||||
|
var x = 100
|
||||||
|
|
||||||
|
// 函数中 查找变量的顺序
|
||||||
|
// 1. 在 函数内部 查找
|
||||||
|
// 2. 在 函数的外部 查找, 一直到全局为止
|
||||||
|
func f1() {
|
||||||
|
fmt.Println(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func f2() {
|
||||||
|
// 局部 作用域
|
||||||
|
// 变量 仅在 该语句块中 生效
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
fmt.Printf("%d\t", i)
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
f1()
|
||||||
|
f2()
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user