SilenceHVK / blog

:books: :octocat: Github static blog post, experience the fun of using Issues.Welcome star( 静态博客文章,体验一下使用 Issues 的乐趣,欢迎 star )个人博客地址:blog.hvkcoder.me/love
https://github.com/SilenceHVK/Articles/issues
MIT License
231 stars 9 forks source link

【Golang 基础】Go 语言的控制语句 #48

Open SilenceHVK opened 6 years ago

SilenceHVK commented 6 years ago

Go 语言的控制语句

判断语句 if-else,支持初始化表达式;

package basic

import "fmt"

func main(){
    if num := 0; num == 0{
        fmt.Println("Zero")
    }else if num == 1 {
        fmt.Println("One")
    }else {
        fmt.Println("Other")
    }
}

循环语句 for,有 3 种形式

package basic

func DoWhile(){
    a := 1

    for{
        a++
        if a > 3 {
            break
        }
    }
}
package basic

func While(){
    a := 1

    for a < 3 {
        a++
    }
}
package basic

func For(){
   for i := 0; i < 3; i++ {  }  
}

  使用 for + if 实现选择排序;

package basic

import "fmt"

func Selection(){
    array := []int{ 10, 25, 1, 6, 2, 5 }

    length := len(array)

    for i := 0; i < length; i++ {
        min := i
        for j := i + 1; j < length; j++ {
            if array[min] > array[j] {
                min = j
            }
        }

        if min != i {
            array[i], array[min] = array[min], array[i]
        }
    }

    fmt.Println(array)
}

控制语句 switch

   switch 支持任何类型或表达式作为条件语句,不需要写 break,条件成立自动终止;需要接着执行下一个 case,使用 fallthrough 语句。

package basic

import "fmt"

func Switch(){
    mark := 60

    // 不加条件判断
    switch mark {
     case 90 :
        fmt.Println("A")
     case 80:
        fmt.Println("B")
     case 70, 60:
        fmt.Println("C")
     default:
        fmt.Println("D")
    }

    // 加入条件判断
    switch {
     case mark >= 90:
        fmt.Println("A")
     case mark < 90 && mark >= 80:
        fmt.Println("B")
     case mark < 80 && mark >= 60:
        fmt.Println("C")
     default:
        fmt.Println("D")
    }
}

goto

  goto 语句可以无条件地转移到当前函数内定义的标签,通常与条件语句配合使用。但是,在结构化程序设计中一般不主张使用 goto,以免造成程序流程的混乱。

package basic

import "fmt"

func GoTo(){
    var a int = 10
    LOOP:
        for a < 20 {
            if a == 15 {
                a = a + 1
                goto LOOP
            }
            fmt.Printf("a的值为 : %d\n", a)
            a++
    }
}