Go语言中的控制语句

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

// 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语言中的控制语句》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

The Haskell School of Expression

The Haskell School of Expression

Paul Hudak / Cambridge University Press / 2000-01 / USD 95.00

Functional programming is a style of programming that emphasizes the use of functions (in contrast to object-oriented programming, which emphasizes the use of objects). It has become popular in recen......一起来看看 《The Haskell School of Expression》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

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

RGB CMYK 互转工具