乐趣区

关于golang:Go-语言变量及常量的定义与使用

变量的定义与应用

package fib_test

import ("fmt") // 引入代码依赖

func TestFibList(t *testing.T) {
    var a int = 1
    var b int = 1
    fmt.Print(a)
    
    for i := 0; i < 5; i++ {fmt.Print(" ", b)
        tmp := a
        a = b
        b = tmp + a
    }
    fmt.Println()
    t.Log("finish.")
}
// 替换两个变量的值
func TestFibList(t *testing.T) {
    a := 1
    b := 1
    a, b = b, a
    t.Log(a, b)
}

常量的定义与应用

package constant_test

import ("fmt") // 引入代码依赖

const (
    Mon = iota + 1
    Tue
    Wed
)

// 位运算
const (
    Readable = 1 << iota
    Writable
    Executable
)

func TestConstant0(t *testing.T) {t.Log(Mon, Tue, Wed)
}

func TestConstant1(t *testing.T) {
    a := 1 //0001,可读
    t.Log(a&Readable == Readable, a&Writable == Writable, a&Executable == Executable)
    
    a := 7 //0111,可读可写可执行
    t.Log(a&Readable == Readable, a&Writable == Writable, a&Executable == Executable)
}
退出移动版