日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Go語言中循環(huán)Loop的用法介紹_Golang

作者:奮斗的大橙子 ? 更新時間: 2022-09-08 編程語言

Go語言和其他語言不一樣,它只有一種循環(huán)方式,就是for語句

可以參考如下公式:

for initialisation; condition; post{
    //Do Something
}

執(zhí)行順序

  • a.執(zhí)行一次initialisation,初始化
  • b.判斷condition
  • c.條件為true,執(zhí)行{}內的語句
  • d.語句執(zhí)行之后執(zhí)行post

使用方式舉例:

1.基本使用類似其他語言的for

func ForTest1(){
   for i:=1;i<=10;i++{
      fmt.Printf("i=%d\t",i)
   }
   fmt.Println()
}

2.替代while語句

func ForTest2(){
   i:=1
   for  ;i<=10; {
      i=i+2
      fmt.Printf("i=%d\t",i)
   }
   fmt.Println()
 
   //等價于
   for i<=10 {
      i=i+2
      fmt.Printf("i=%d\t",i)
      fmt.Println()
   }
}

3.多條件(多重賦值)

func ForTest3(){
   for x,y:=1,10; x<10 && y>1; x,y = x+1,y-1{
      fmt.Printf("x=%d\t",x)
      fmt.Printf("y=%d\t",y)
      fmt.Println()
   }
   fmt.Println()
}

4.無限循環(huán)

func ForTest4(){
   count:=1
   for {
      fmt.Printf("Hello\t")
      if(count == 3){
         break
      }
      count++
   }
}

運行結果如下:

-----ForTest1-------
i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10 ??
-----ForTest2-------
i=3 i=5 i=7 i=9 i=11 ??
-----ForTest3-------
x=1 y=10 ??
x=2 y=9
x=3 y=8
x=4 y=7
x=5 y=6
x=6 y=5
x=7 y=4
x=8 y=3
x=9 y=2
-----ForTest4-------
Hello ? Hello ? Hello

原文鏈接:https://www.cnblogs.com/dcz2015/p/10443055.html

欄目分類
最近更新