作用域
universe block > package block > file block > function block > inner block
universe block
预声明的标识符。Go文件全部使用
1 2 3 4 5 6 7 8 Types: bool byte complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune string uint uint8 uint16 uint32 uint64 uintptr Constants: true false iota Zero value: nil Functions: append cap close complex copy delete imag len make new panic print println real recover
package block
例子 fmt下面的函数println 就是package scope
1 2 3 4 5 6 7 8 9 10 package mainimport "fmt" var x int =5 func main () { fmt.Println("mainx:" ,x) }
外部变量是package block:
下面的代码有效:
1 2 3 4 5 6 7 8 9 10 11 package mainvar x int package mainfunc f () { fmt.Println(x) }
调用另一个包中的函数和属性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 package testdemoimport "fmt" var Birth uint = 23 func Haha () { fmt.Println("lalalal" ) } package main import ( "testdemo" "fmt" ) func main () { testdemo.Haha() fmt.Println(testdemo.Birth) }
权限
如果要让包中的属性和变量被外部包调用,必须要首字母大写。
file block
下面的代码无效,因为import 是file block 。不能跨文件
1 2 3 4 5 6 7 8 9 10 package mainimport "fmt" package mainfunc f () { fmt.Println("Hello World" ) }
function block
函数体内部的变量是function block,注意前后顺序,同时不能跨函数使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 func main () { fmt.Println("Hello World" ) x := 5 fmt.Println(x) } func main () { fmt.Println("Hello World" ) fmt.Println(x) x := 5 } func main () { fmt.Println("Hello World" ) x := 5 fmt.Println(x) } func test () { fmt.Println(x) }
函数内部变量与外部变量重名
就近原则
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package mainimport "fmt" var x int =5 func test () { var x int = 99 ; x = 100 ; fmt.Println("testx" ,x) }
inner block
在花括号中声明的变量只在花括号中有效。
1 2 3 4 5 6 7 8 //内部变量 func main() { fmt.Println("Hello World") // x is out of scope { // x is out of scope x := 5 // x is in scope fmt.Println(x) // x is in scope } // x is out of scope again }
下面代码无效:
1 2 3 4 5 6 func main() { { x := 5 } fmt.Println(x) }
参考资料:
Variables
灾难总是接踵而至,这正是世间的常理。你以为只要哭诉一下,就会有谁来救你?如果失败了,就只能说明我不过是如此程度的男人