• go入门2 --- 控制流


    对于go来讲控制流也就那么几个:

    1.if 

    这就是一个最简单的if判断,if 初始化语句,判断条件{}, else if, else 必须紧跟上面条件结束的花括号,不能另起一行

    func main() {
    if x := 10; x>1{
    fmt.Println(x)
    }else if x > 0{
        ...
      } else {
        ...
      }
    }

    go 不支持三元运算,这确实是一个比较可惜的地方

    2.for循环

    func main() {
    
        x := "i am good person"
        for i, n := 0, len(x); i < n; i++{  // len(x) 如果经常使用,尽量放到初始化语句中
            fmt.Println(x[i], i ,n)
        }
    
    }

    go 中没有while,直接使用for{}起个死循环就可以,想要打断,直接break

    3.range

    类似于迭代器的操作,搭配for循环使用

    func main() {
    
        x := []string{"i", "am", "good", "person"}
        for index, v := range x{  // index如果用不到,可以使用  _
            fmt.Println(index, v)
        }
    }

    4.switch

    分支表达式可以是任意的类型,默认会自动终止,不需要break,default是所有都找不到的情况下,执行,当然还有fallthrough,意味着我这个分支执行完毕,也会吧下一个分支执行,不会进行判断条件

    func main() {
        var (
            x = []string{"a", "b"}
            y = "a"
        )
        switch y {
        case x[0]:
            fmt.Println("first")
        case x[1]:
            fmt.Println("two")
        default:
            fmt.Println("not found")
        }
    
    }

    4.goto

    这个就是函数内跳转,大小写敏感,当 i > 10 就会执行 BREAK标签,如果标签使用了但是没有执行也会报错

    func main() {
        var i int
        for {
            i ++
            if i >10 {goto BREAK}
        }
        BREAK:
            fmt.Println("over", i)
    }

    5.break, continue

    当y大于3是就是从L2重新执行

    当x大于2时就会打断L1,循环结束

    func main() {
    L1:
        for x := 0; x < 100; x++ {
        L2:
            for y := 0; y < 100; y++ {
                if y > 3 {
                    continue L2
                }
                if x > 2 {
                    break L1
                }
                fmt.Println(x, y)
            }
            fmt.Println()
        }
    
    }
  • 相关阅读:
    faster with MyISAM tables than with InnoDB or NDB tables
    w-BIG TABLE 1-toSMALLtable @-toMEMORY
    Indexing and Hashing
    MEMORY Storage Engine MEMORY Tables TEMPORARY TABLE max_heap_table_size
    controlling the variance of request response times and not just worrying about maximizing queries per second
    Variance
    Population Mean
    12.162s 1805.867s
    situations where MyISAM will be faster than InnoDB
    1920.154s 0.309s 30817
  • 原文地址:https://www.cnblogs.com/yangshixiong/p/12120395.html
Copyright © 2020-2023  润新知