Go 第二部分:分支语句、函数

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Go 第二部分:分支语句、函数脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

这是 Go 系列的第二篇文章,主要介绍 if/else , swITch 和函数的各种用法。

系列整理:

如果对 Go 语言本身感兴趣,可以阅读我的这篇译文 Go语言的优点,缺点和令人厌恶的设计

if/else

// 声明可以先于条件,if 中的声明的变量只在此 if/else 有效
if num := 9; num < 0 {
    
} else if num < 10 {
    
} else {
    
}

switch

// 普通 switch
switch time.Now().Weekday() {
    // 可以用逗号写多个值
    case time.Saturday, time.Sunday:
        fmt.Println("It's the weekend")
    default:
        fmt.Println("It's the weekday")
}


// 无表达式额的 switch
switch {
    case t.Hour() < 12:
        fmt.Println("It's before noon")
    default:
        fmt.Println("It's after noon")
}

// 比较类型
whatami := func(i interface{}) {
    switch t := i.(type) {
        case bool:
            fmt.Println("I'm a bool")
        case int:
            fmt.Println("I'm a int")
        default:
            fmt.Printf("Don't know type %Tn", t)    
    }
}

whatamI(true)
whatAmI(1)
whatAmI("hey")

循环

// 经典的循环
for n := 0; n <= 5; n++ {
    if n % 2 == 0 {
        continue
    }
    fmt.Println(n)
}

// 只有条件
for i <= 3 {
    fmt.Println(i)
    i = i + 1 
}

// 死循环
for {
    fmt.Println("loop")
    break
}

实际测试

将整数转换为二进制表示

func convertToBin(v int) string {
    result := ""
    for ; v > 0; v /= 2 {
        result = strconv.Itoa(v % 2) + result
    }
    
    return result
}

函数

// 闭包函数
func apply(op func(int, int) int, a, b int) int {
    return op(a, b)
}

func main() {
    result := apply(func(i int, i2 int) int {
        return int(math.Pow(float64(i), float64(i2)))
    }, 2, 2)

    fmt.Println(result)
}

// 可变参数
func sum(num ... int) int {
    VAR result = 0
    for _, v := range num {
        result = result + v
    }
    return result
}

c := sum(1, 2, 3)

fmt.Println(c)

脚本宝典总结

以上是脚本宝典为你收集整理的Go 第二部分:分支语句、函数全部内容,希望文章能够帮你解决Go 第二部分:分支语句、函数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。