Go学习交流

GO学习笔记01

2018-03-22  本文已影响7人  Q大疯zi

一、变量、常量

1.注意事项

导包必须使用、声明的变量必须使用、变量可以不赋值,默认值是系统默认值。

2.变量的声明和赋值

    package main
    
    import "fmt"
    
    func main() {
        var a int
        a = 20
        fmt.Println("a 的值是", a)
    
        c := 30     //自动推导类型
        fmt.Printf("c type is %T\n", c)
    }
    
    
    a 的值是 20
    c type is int
    //Println是换行输出  Printf是格式化输出

3.多重赋值

        i, j := 10, 20
        i, j = j, i
        fmt.Printf("i = %d , j = %d \n", i, j)
        
        //实现快速交换两个变量的值

4.匿名变量

    package main
    
    import "fmt"
    
    func main() {
        var o, p, q int
        o, p, q = test()
        fmt.Printf("o = %d, p = %d,q = %d\n", o, p, q)
    
        //_代表匿名变量,可以忽略一个返回值
        o, _, q = test()
        fmt.Printf("o = %d,q = %d\n", o, q)
    
    }
    
    
    func test() (a, b, c int) {
        return 1, 2, 3
    }

5.常量

    package main
    
    import "fmt"
    
    func main() {
       const a = 10
       fmt.Println("a的值是", a)   //常量不允许再次赋值
        
        const b = 11.2 //常量不用加冒号 const b: = 11.2
        fmt.Printf("b type is %T\n", b)
        fmt.Println("b =", b)
    }

6.声明的时候简单写法

    package main
    
    import "fmt"
    
    func main() {
        //var a int
        //var b float64
        
        //也可以这样写 ,常量也一样
        var (
            a int
            b float64
        )
        a, b = 10, 3.14
        fmt.Println("a = ", a)
        fmt.Println("b = ", b)
    
    }

二、枚举

    package main
    
    import "fmt"
    
    func main() {
        //1.iota常量自动生成器,每隔一行自动累加1
        //2.iota给常量赋值使用
        const (
            a = iota //0
            b = iota //1
            c = iota //2
            d = iota //3
        )
        fmt.Printf("a = %d , b =  %d , c = %d,d = %d\n", a, b, c, d)
    
        //3.iota遇到const重置为0
        const e = iota
        fmt.Printf("e = %d\n", e)
    
        //4.可以只写一个iota
        const (
            a1 = iota //0
            b1
            c1
        )
        fmt.Printf("a1 = %d , b1 = %d , c1 = %d\n", a1, b1, c1)
    
        //5.在同一行的iota值一样
        const (
            o          = iota
            p1, p2, p3 = iota, iota, iota
            q          = iota
        )
        fmt.Printf("o = %d ,p1 = %d,p2= %d,p3 = %d,q = %d", o, p1, p2, p3, q)
    
    }
上一篇下一篇

猜你喜欢

热点阅读