go语言中间的循环

在Go语言中只有很少的几个控制结构,它没有while或者do-while循环。

但是它有for、switch、if。而且switch接受像for那样可选的初始化语句。下面来认识一下他们

一、if语句

Go语言中的if像下面这个样子:

if x > 0 {
    return y
} else {
    return x
}

一般不需要加圆括号,不过,如果你写上,也是没有问题的(亲测,写上圆括号也可以的~~)。比如:

复制代码
if (3>2) {
        fmt.Println("test if")
}else if true {
        fmt.Println("test else if")
}else{
        fmt.Println("test else")
}

//输出 test if
复制代码

二、switch语句

Go的switch非常灵活。表达式不必是常量或整数。
而在java中switch后面的括号里面只能放int类型的值,注意是只能放int类型,但是放byte,short,char类型的也可以,

那是因为byte,short,shar可以自动提升(自动类型转换)为int,也就是说,你放的byte,short,shar类型,然后他们会自动转换为int类型(宽化,自动转换并且安全),
其实最后放的还是int类型!

switch语句执行的过程从上至下,直到找到匹配项,匹配项后面也不需要再加break(又跟java不一样哦!)

复制代码
func switchFuncString(a string) {
    //字符串
    switch a {
    case "test1":
        fmt.Println("test1")
    case "test2", "test3":
        fmt.Println("testOhter")
    default:
        fmt.Println("NoTest")
    }

}

func switchFuncInt(a int) {
    //数字
    switch a {
    case 1:
        fmt.Println("1")
    case 2:
        fmt.Println("2")
    case 3:
        fmt.Println("3")
    }
}

func switchFuncBool(c byte) {
    //switch后面什么都没有?它会匹配true
    switch {
    case '0' <= c && c <= '9':
        fmt.Println(c - '0')
    case 'a' <= c && c <= 'f':
        fmt.Println( c - 'a' + 10)
    case 'A' <= c && c <= 'F':
        fmt.Println( c - 'A' + 10)
    }
}
复制代码

但是如果,你就希望匹配之后,继续匹配下面一条怎么办呢?还是有办法的,使用“fallthrough”即可,例如:

复制代码
func switchFuncInt(a int) {
    //数字
    switch a {
    case 1:
        fmt.Println("1")
        fallthrough 
    case 2:
        fmt.Println("2")
    case 3:
        fmt.Println("3")
    }
}
复制代码

调用switchFuncInt(1),打印出1和2来。

三、for循环

Go语言的For循环油3中形式,只有其中的一种使用分号。

  1. for init; condition; post { }          和C 的for 一样
  2. for condition { }                         和while 一样
  3. for { }                                      和C 的for(;;) 一样(死循环)

直接上代码~~

复制代码
package main

import "fmt"

func main() {
    simpleFor()

    var test string = "asdfghjkl"
    fmt.Println(reverse([]byte(test)))
}

//打印0~9
func simpleFor() {
    for i := 0; i < 10; i++ {
        fmt.Println(i)
    }
}

// Reverse a
func reverse(a []byte) string {
    //由于Go没有逗号表达式,而++和--是语句而不是表达式,
    //如果你想在for中执行多个变量,应当使用平行赋值。
    for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
        a[i], a[j] = a[j], a[i]
    }
    return string(a)
}
复制代码

分支、循环是很基础的东西,所以有必要多练练手~~

下面来做两个题目玩玩~~

1. 创建一个基于for的简单的循环。使其循环10次,并且使用fmt 包打印出计数器的值。
2. 用goto改写1的循环。保留字for不可使用。
3. 再次改写这个循环,使其遍历一个array,并将这个array打印到屏幕上。

代码:

原文地址:https://www.cnblogs.com/zhangym/p/5580194.html