变量声明
可以一次声明多个变量:
1 | var identifier1, identifier2 type |
实例2
1 | package main |
以上实例输出结果为:
1 | test |
数值类型(包括complex64/128)为 0
布尔类型为 false
字符串为 “”(空字符串)
以下几种类型为 nil:
1
2
3
4
5
6var a *int
var a []int
var a map[string] int
var a chan int
var a func(string) int
var a error // error 是接口
实例
1 | package main |
输出结果是:
1 | 0 0 false "" |
根据值自行判定变量类型
1 | var v_name = value |
实例
1 | package main |
输出结果是:
1 | true |
省略 var
Inside a function, the :=
short assignment statement can be used in place of a var
declaration with implicit type.
Outside a function, every statement begins with a keyword (var
, func
, and so on) and so the :=
construct is not available.
注意 *:=* 左侧如果没有声明新的变量,就产生编译错误,格式:
1 | v_name := value |
例如:
1 | var intVal int |
可以将 var f string = “Runoob” 简写为 f := “Runoob”:
实例
1 | package main |
输出结果是:
1 | Runoob |
多变量声明
1 | //类型相同多个变量, 非全局变量 |
实例
1 | package main |
以上实例执行结果为:
1 | 0 0 0 false 1 2 123 hello 123 hello |
常量声明(const)
1 | const identifier [type] = value |
你可以省略类型说明符 [type],因为编译器可以根据变量的值来推断其类型。
- 显式类型定义:
const b string = "abc"
- 隐式类型定义:
const b = "abc"
多个相同类型的声明可以简写为:
1 | const c_name1, c_name2 = value1, value2 |
以下实例演示了常量的应用:
实例
1 | package main |
以上实例运行结果为:
1 | 面积为 : 50 |
Default Values
Variables declared without an explicit initial value are given their zero value.
The zero value is:
0
for numeric types,false
for the boolean type, and""
(the empty string) for strings.
1 | package main |
变量作用域
局部变量
在函数体内声明的变量称之为局部变量,它们的作用域只在函数体内,参数和返回值变量也是局部变量。
以下实例中 main() 函数使用了局部变量 a, b, c:
实例
1 | package main |
以上实例执行输出结果为:
1 | 结果: a = 10, b = 20 and c = 30 |
全局变量
在函数体外声明的变量称之为全局变量,全局变量可以在整个包甚至外部包(被导出后)使用。
全局变量可以在任何函数中使用,以下实例演示了如何使用全局变量:
实例
1 | package main |
以上实例执行输出结果为:
1 | 结果: a = 10, b = 20 and g = 30 |
Go 语言程序中全局变量与局部变量名称可以相同,但是函数内的局部变量会被优先考虑。实例如下:
实例
1 | package main |
以上实例执行输出结果为:
1 | 结果: g = 10 |
形式参数
形式参数会作为函数的局部变量来使用。实例如下:
实例
1 | package main |
以上实例执行输出结果为:
1 | main()函数中 a = 10 |
初始化局部和全局变量
不同类型的局部和全局变量默认值为:
数据类型 | 初始化默认值 |
---|---|
int | 0 |
float32 | 0 |
pointer | nil |