Golang 中的 Foreach 迴圈
    
    
            Jay Singh
    2023年1月30日
    
    Golang
    Golang foreach loop
    
 
本文將展示使用 Go 程式語言中的函式實現 foreach 迴圈的各種示例,並簡要討論 Golang 和使用的函式。
在 Golang 中使用 slice 函式實現 foreach 迴圈
    
foreach 關鍵字在 Go 中不存在;儘管如此,for 迴圈可以擴充套件來實現同樣的目的。
區別在於 range 關鍵字與 for 迴圈一起使用。你可以在迴圈中使用 slices 鍵或值,就像許多其他語言中的 foreach 迴圈一樣。
示例 1:
package main
//import fmt package
import (
	"fmt"
)
//program execution starts here
func main() {
	//declare and initialize slice
	fruits := []string{"mango", "grapes", "banana", "apple"}
	//traverse through the slice using for and range
	for _, element := range fruits {
		//Print each element in new line
		fmt.Println(element)
	}
}
輸出:
mango
grapes
banana
apple
在上面的例子中,我們遍歷了一片 fruit。之後,我們使用 for-range 在新行上列印每個元素。
示例 2:
在本例中,我們通過遍歷字串 slice 來列印每個單詞。我們使用下劃線 _ 代替鍵,因為我們需要值。
package main
import "fmt"
func main() {
	myList := []string{"rabbit", "dog", "parrot"}
	// for {key}, {value} := range {list}
	for _, animal := range myList {
		fmt.Println("My animal is:", animal)
	}
}
輸出:
My animal is: rabbit
My animal is: dog
My animal is: parrot
在 Golang 中使用 map 函式實現 foreach 迴圈
陣列可以迭代和迴圈遍歷 map 中的每個元素。Golang Maps 是一組不以任何方式排序的鍵值對。
它廣泛用於快速查詢和可以使用鍵檢索、更新或刪除的值。
例子:
package main
import "fmt"
func main() {
	myList := map[string]string{
		"dog":      "woof",
		"cat":      "meow",
		"hedgehog": "sniff",
	}
	for animal, noise := range myList {
		fmt.Println("The", animal, "went", noise)
	}
}
輸出:
The cat went meow
The hedgehog went sniff
The dog went woof
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe