1.基础定义
变量类型在变量名后
var a intvar s string
2.定义并赋值
var a,b int = 1,2var s string="abc"
3.类型推导
不用定义变量类型
var a,b,c,s = 1,2,true,"deduction"
4.简写(只能在函数内)
用":="代替"var"
a,b,c,s := 1,2,true,"deduction"
5.定义多个变量并赋值
var( a1=1 s1="package" c1=false)
测试代码
package mainimport "fmt"/* 包内变量,定义多个并赋值 */var( a1=1 s1="package" c1=false)/* 只定义不赋值 */func variableZeroValue() { var a int var s string fmt.Printf("%d %q\n", a,s) }/* 定义并赋值 */func variableInitialValue() { var a,b int = 1,2 var s string ="abc" fmt.Println(a,b,s) }/* 类型推导 */func variableTypeDeduction() { var a,b,c,s = 1,2,true,"deduction" fmt.Println(a,b,c,s) }/* 简写(只能函数内使用) */func variableShorter(){ a,b,c,s := 1,2,true,"deduction" b=1 fmt.Println(a,b,c,s) }func main() { fmt.Println("hello word") variableZeroValue() variableInitialValue() variableTypeDeduction() variableShorter() fmt.Println(a1,s1,c1) }
原文出处:https://www.cnblogs.com/lz120792/p/9551877.html