變量定義要求 :Go 語言變量名由字母、數字、下劃線組成,其中首個字符不能爲數字ide
在描述變量定義以前,先描述下go 語言的結構code
package main import "fmt" import "math" func main() { // 定義單一變量 var age =18 fmt.Println("my age is ",age) } 輸出:my age is 18
// 定義多個變量 var width,height int = 100,50 fmt.Println("width is ",width,"height is",height) 輸出: width is 100 height is 50
var ( name = "zhangsan" age = 18 job = "go" salary int ) fmt.Println(" his name is",name, "age is",age, "job is",job, "salary is",salary) 輸出: his name is zhangsan age is 18 job is IT salary is 0
go 的簡短聲明it
簡短聲明的要求, := 左邊的變量都有初始值 ,不然報錯 例如 assignment mismatch: 3 variable but 2 valuesclass
name,age,job := "zhangsan",18,"IT" fmt.Println(name,age,job) 輸出 :zhangsan 18 IT
簡短聲明的語法要求 := 操做符的左邊至少有一個變量是還沒有聲明的import
x,y :=20,30 fmt.Println("x is",x,"y is ",y) y,z := 40,50 fmt.Println("y is",y,"z is ",z) 正常輸出: x is 20 y is 30 y is 40 z is 50 x,y :=20,30 x,y := 40,58 fmt.Println("x is",x ,"y is",y) 報錯 no new variables on left side of :=,左邊並無還沒有聲明的變量