2.3 if switch for等流程控制

if条件中可以写多个语句,语句的作用域仅限于if,不可在if之外的地方使用

package main

import (
    "fmt"
    "io/ioutil"
)

func if1(){
    const filename = "/home/tidb/IdeaProjects/msdb/msdb/src/study/ifswitch.go"
    if txt, err := ioutil.ReadFile(filename); err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("%s
", txt)
    }
}

func switch1(level int) string{
    res := ""

    switch level{
    case 1:
        res = "100000"
    case 2:
        res = "30000"
    case 3:
        res = "10000"
    default:
        res = "1000"
    }
    return res
}
func switch2(level int) string{
    res := ""

    switch {
    case level == 100:
        res = "100000"
    case level > 90:
        res = "30000"
    case level > 80:
        res = "10000"
    case level > 60:
        res = "1000"
    case level <= 60:
        panic("You ......")
    }
    return res
}

func main() {
    //if1()
    res := switch1(1)
    println(res)
    fmt.Println(switch1(1),switch1(2))  
    fmt.Println(switch2(100),switch2(88),switch2(38))
}

for 循环数字

for i:= 0;i<9;i++ {
            fmt.Println(i)
        }

for 永远循环,死循环中通常会有跳出循环的条件

 for {
        record, err := r.Read()
        
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }
        for i:= 0;i<r.FieldsPerRecord;i++ {
            fmt.Println(i,record[i])
        }
    }

for输出数组

for index, val := range arr{
        fmt.Printf("第 %d 位 x 的值 = %d
", index,val)
    }

for输出map

for key, value := range oldMap {
    newMap[key] = value
}
原文地址:https://www.cnblogs.com/perfei/p/10480393.html