Go语言中的控制语句

栏目: Go · 发布时间: 6年前

// code_004_process_control project main.go
package main

import (
    "fmt"
    "time"
)

func main() {
    //if语句
    if a := 3; a > 3 {
        fmt.Println("a >3")
    } else if a == 3 {
        fmt.Println("a==3")
    } else {
        fmt.Println("error")
    }

    fmt.Println("\n============\n")
    //switch语句1
    switch score := 90; score {
    case 80, 90, 100:
        fmt.Println("优秀")
    case 50, 60, 70:
        fmt.Println("及格")
    default:
        fmt.Println("差")
    }
    //switch语句2
    var score int = 90
    switch score {
    case 80, 90, 100:
        fmt.Println("优秀")
    case 50, 60, 70:
        fmt.Println("及格")
    default:
        fmt.Println("差")
    }
    //switch语句3
    switch s3 := 90; {
    case s3 >= 90:
        fmt.Println("优秀")
    case s3 >= 80:
        fmt.Println("良好")
    default:
        fmt.Println("一般")
    }

    fmt.Println("\n============\n")
    //最简单的无限循环
    for {
        time.Sleep(3 * time.Second)
        fmt.Println("for循环结束")
        break
    } //相当于 python 中while True: java中的for(;;){}

    //for循环
    var i, sum int
    for i = 1; i <= 100; i++ {
        fmt.Printf("i=%d\n", i) //Printf()格式化输出,Println()无法格式化
        sum += i
    }
    fmt.Println("sum =", sum)

    //for ... range...
    s := "abc"
    for i := range s { //支持str/array/slice/map--->>只能获取到index的值
        fmt.Printf("%c\n", s[i])
    }
    for _, c := range s { //忽略index
        fmt.Printf("%c\n", c)
    }
    for i, c := range s {
        fmt.Printf("第%d个值为:%c\n", i, c)
    }

    //for ... break 或者continue
    for i := 0; i < 5; i++ {
        if i == 2 {
            fmt.Printf("i== 2时 跳出本次循环")
            break
        }
        fmt.Println(i)
    }
    for i := 0; i < 5; i++ {
        if 2 == i {
            fmt.Println("哈哈,你看不到我,你真2")
            continue
        }
        fmt.Println(i)
    } //备注:break 可以用for、switch、select,而continue仅能用于for循环

    //goto,用goto跳转到必须在当前函数内定义的标签:
    fmt.Println("\n============\n")
    for i := 0; i < 5; i++ {
        for {
            fmt.Println(i)
            goto LABEL //跳转到标签LABEL,从标签处,执行代码
        }
    }
    fmt.Println("Let's see goto LABEL!!!")

LABEL:
    fmt.Println("it is over")

}

以上所述就是小编给大家介绍的《Go语言中的控制语句》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Zero to One

Zero to One

Peter Thiel、Blake Masters / Crown Business / 2014-9-16 / USD 27.00

“This book delivers completely new and refreshing ideas on how to create value in the world.” - Mark Zuckerberg, CEO of Facebook “Peter Thiel has built multiple breakthrough companies, and ......一起来看看 《Zero to One》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具