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

學無先后,達者為師

網站首頁 編程語言 正文

詳解Go語言中for循環,break和continue的使用_Golang

作者:孫琦Ray ? 更新時間: 2022-08-22 編程語言

基本語法

和C語言同源的語法格式,有始有終的循環,for init; condition; post { }

帶條件的while循環,for condition { }

無限循環,for { }

有始有終的條件循環

sum := 0
for i := 0; i < 10; i++ {
    sum = sum + i
}

注意:i變量在循環結束后無法使用

帶條件的循環

count := 0
for count < 10 {
    fmt.Printf("Current count = %v\n", count)
    count++
}

無限循環

由于循環不會停止,這里使用break來中斷循環,后面還會詳細介紹

 count := 0
 for {
     fmt.Printf("current count = %v\n", count)
     count++

     if count > 10 {
         break
     }
 }

數組循環

使用計數器循環

類似C語言中的循環,我們可以通過計數器結合數組長度實現對數組的遍歷,同時能獲取數組索引,如下面例子所示

package main

import "fmt"

func main() {
    myarray := []string{"a", "b", "c", "d"}

    for i := 0; i < len(myarray); i++ {
        fmt.Printf("Array index is %v, value is %v\n", i, myarray[i])
    }
}

利用range循環

利用range可以更容易的進行循環,并且range還能用于slice,channel和map的循環中

package main

import "fmt"

func main() {
    myarray := []string{"a", "b", "c", "d"}

    for index, item := range myarray {
        fmt.Printf("current index is %v, value is %v\n", index, item)
    }
}

Map循環

在介紹Map時,我們已經嘗試用for循環對Map進行遍歷,我們再來鞏固一下

package main

import "fmt"

func main() {
    mymap := map[int]string{1 : "a", 2 : "b", 3 : "c"}

    for key, value := range mymap {
        fmt.Printf("current key is %v, value is %v\n", key, value)
    }
}

如果只想獲取key,則可以使用,省略value

for key := range mymap {

或者使用_,前面介紹過_無法用于變量,像個占位符

for _, value := range mymap {

string的遍歷

下面的示例是對string類型的遍歷,除了普通的字符,對于Unicode字符切分,字符通常是8位的,UTF-8的字符最高可能是32位的

package main

import "fmt"

func main() {
    mystr := "abc"
    for pos, char := range mystr {
        fmt.Printf("character '%c' starts at byte position %d\n", char, pos)
    }

    for pos, char := range "G?!" {
        fmt.Printf("character '%c' starts at byte position %d\n", char, pos)
    }
}

character 'G' starts at byte position 0
character '?' starts at byte position 1
character '!' starts at byte position 3

Break和Continue

與大部分語言一致

  • Break結束當前循環
  • Continue開始下一次循環
package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        if i == 3 {
            fmt.Printf("For continue at here: %d\n", i)
            continue
        }
        if i > 5 {
            fmt.Printf("For break at here: %d\n", i)
            break
        }
        fmt.Printf("Current for count: %d\n", i)
    }

    fmt.Println("For loop end here")
}

輸出結果

Current for count: 0
Current for count: 1
Current for count: 2
For continue at here: 3
Current for count: 4
Current for count: 5
For break at here: 6
For loop end here

不推薦方式

Go中也支持Lable方式,類似Goto,一般不使用

J:  for j := 0; j < 5; j++ {
             for i := 0; i < 10; i++ {
                 if i > 5 {
                     break J
                 }
                 fmt.Println(i)
             }
         }

原文鏈接:https://blog.csdn.net/xiaoquqi/article/details/125532904

欄目分類
最近更新