GO(2)-for if-else switch defer

控制语句 for,if-else,switch,defer语法MARK一下。
1.for
 

for init;condition;end{//init在第一次运行前执行,condition是条件判断
       circle body
                      }
package main
import "fmt"
func main(){ 
    sum1:=0 //初始化  
    for i:=0;i<10;i++{
        sum1+=i
    }
    sum2:=1
    for sum2<100{
        sum2*=2
    }
    sum3:=1
    for{
        if sum3<100{
            sum3=2
        }else
        {break
        }
    }
    fmt.Println(sum1,sum2,sum3)
    }


2. if-else
 

if condition1{
    branch1
}else if condition2{
     branch2
}else
{
    branch3
}

3. switch
 

package main
import (
    "fmt"
    "time"
)
func main(){ 
    nowTime:=time.Now()
    switch nowTime.Weekday(){
        case time.Saturday:
        fmt.Println("take a rest")
        case time.Sunday:
        fmt.Println("take a rest")
        default:
        fmt.Println("you need to work")
    }
    switch{ case nowTime.Weekday()>=time.Monday&&
                 nowTime.Weekday()<=time.Friday;
             fmt.Println("you need to work")
            default:
           fmt.Println("take a rest")
          }
        }
    }


4.defer 延迟执行 先进后出的顺序。

package main
import "fmt"
func add(a,b int)int{
    return a+b
}
//按照先进后出的结果 11 7 3
func main(){
    a:=1
    b:=2
    defer fmt.Println("front result:",add(a,b))//3
    a=3
    b=4
    defer fmt.Println("last result:",add(a,b))//7
    a=5
    b=6
    fmt.Println(add(a,b))//11
}


 

猜你喜欢

转载自blog.csdn.net/aggie4628/article/details/107465933
今日推荐