gpt4 book ai didi

go - 以下哪些是 Go 中用于控制循环的有效关键字?

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:33 25 4
gpt4 key购买 nike

我看到这个问题的正确答案是“for and range”。

但是 for 语句是 Go 中唯一可用的循环语句,并且 range 关键字允许您迭代列表的项目,如数组或映射。为了理解它,您可以将 range 关键字翻译成for each index of

//for loop
package main

import "fmt"

func main() {
for i := 0; i < 5; i++ {
fmt.Println("Value of i is now:", i)
}
}

//range is used inside a for loop


a := [...]string{"a", "b", "c", "d"}
for i := range a {
fmt.Println("Array item", i, "is", a[i])
}
capitals := map[string] string {"France":"Paris", "Italy":"Rome", "Japan":"Tokyo" }
for key := range capitals {
fmt.Println("Map item: Capital of", key, "is", capitals[key])
}

//range can also return two items, the index/key and the corresponding value
for key2, val := range capitals {
fmt.Println("Map item: Capital of", key2, "is", val)
}

最佳答案

我认为问题是关于不同形式的 For 循环:
简单的循环变体工作示例:

package main

import "fmt"

func main() {
//0 1 2 3 4 5 6 7 8 9
for i := 0; i < 10; i++ {
fmt.Print(i, " ")
}
fmt.Println()

i := 0
for ; i < 10; i++ {
fmt.Print(i, " ")
}
fmt.Println()

for i := 0; i < 10; {
fmt.Print(i, " ")
i++
}
fmt.Println()

//2 4 6 8 10 12 14 16 18 20
for i := 1; ; i++ {
if i&1 == 1 {
continue
}
if i == 22 {
break
}
fmt.Print(i, " ")
}
fmt.Println()

i = 0
for {
fmt.Print(i, " ")
i++
if i == 10 {
break
}

}
fmt.Println()

for i, j := 0, 0; i < 5 && j < 10; i, j = i+1, j+2 {
fmt.Println(i, j)
}
}

对于数组、 slice 、字符串、映射、 channel ,使用 range 关键字:

package main

import "fmt"

func main() {
ary := [5]int{0, 1, 2, 3, 4}
for index, value := range ary {
fmt.Print("ary[", index, "] =", value, " ")
}
fmt.Println()
for index := range ary {
fmt.Print("ary[", index, "] =", ary[index], " ")
}
fmt.Println()
for _, value := range ary {
fmt.Print(value, " ")
}
fmt.Println()

slice := []int{20, 21, 22, 23, 24, 25, 26, 27, 28, 29}
for index, value := range slice {
fmt.Println("slice[", index, "] =", value)
}
fmt.Println()

str := "Hello"
for index, value := range str {
fmt.Println("str[", index, "] =", value)
}
fmt.Println()

mp := map[string]int{"One": 1, "Two": 2, "Three": 3}
for key, value := range mp {
fmt.Println("map[", key, "] =", value)
}
fmt.Println()

ch := make(chan int, 10)
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)

for i := range ch {
fmt.Print(i, " ")
}
fmt.Println()
}

和标签为 break 标签和 continue 标签:

package main

import "fmt"

func main() {
a, b := 1, 1
Loop1:
for {
b++
Loop2:
for {
a++
switch {
case a == 2:
fallthrough
case a == 3:
fmt.Println(3)
case a == 4, a == 5:
continue
case a == 7:
continue Loop1
case a == 9:
break Loop2
case a == 10:
break Loop1
case a == 8:
break
default:
fmt.Println(a, b)
}
}
}
}

关于go - 以下哪些是 Go 中用于控制循环的有效关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37484049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com