学Go第二天

今天了解了go语言变量和常量的声明,关键字var,const,iota

变量var声明:

//变量声明
//var name string
//var age int
//var isOk bool

//批量声明变量
var (    
name string    
age  int    
isOK bool)
func main() {    
name = "Zeddda"    
age = 20    
isOK = true    
//Go语言中非全局变量声明必须使用,不使用就编译不过去
fmt.Printf("name:%s\n", name)    
fmt.Print(isOK)    
fmt.Println(age)
   
var s1 string = "zed"    
fmt.Println(s1)    
s2 := "hhh"//简短函数变量,只能在函数内使用    
fmt.Println(s2)    
var s3 = "20"//类型推导(根据值判断变量类型)    
fmt.Println(s3)     
  //匿名变量是一个特殊变量:_}
  

运行结果
D:\Go语言\src\github.com\Zed\day02\var>var.exe
name:Zeddda
true20
zed
hhh
20

常量const声明:

//定义常量后不能修改
const pi = 3.1415926
//iota是const计数器,遇到const重置为0 
const(    
   a1 = iota    
   a2 = iota    
   a3 = iota
   )
const(    
 b1 = iota  //0    
 b2 = iota  //1    
 _  = iota  //2    
 b3 = iota  //3
)
//插队
const(    
c1 = iota //0    
c2 = 100 //100    
c3 = iota //2
)
//多个常量声明在一行
const(    
   d1,d2 = iota+1,iota+2 //d1=1,d2=2    
   d3,d4 = iota+3,iota+4 //d3=4,d4=5)func main(){
    const(        
    n1 = 100        
    n2        
    n3    
    )     
    fmt.Println("n1:",n1)    
    fmt.Println("n2:",n2)    
    fmt.Println("n3:",n3)
    fmt.Println("a1:",a1)    
    fmt.Println("a2:",a2)    
    fmt.Println("a3:",a3)
    fmt.Println("d1:",d1)    
    fmt.Println("d2:",d2)    
    fmt.Println("d3:",d3)    
    fmt.Println("d4:",d4)    
    const(        
    s1 = 13        
    s2 = 15            
    )    
    fmt.Println("s1:",s1)    
    fmt.Println("s2:",s2)        
    


运行结果
n1: 100
n2: 100
n3: 100
a1: 0
a2: 1
a3: 2
d1: 1
d2: 2
d3: 4
d4: 5
s1: 13
s2: 15

iota是常量const计数器,遇到const重置为0
Go语言中非全局变量声明必须使用,不使用就编译不过去

加油!

你可能感兴趣的:(go,golang)