Golang的slice、map、array的for循环的总结

/ golang / 没有评论 / 77浏览

map

package main
import (
	"fmt"
)
func main() {
	var name map[string]string
	name = map[string]string{"name1": "adou", "name2": "menghu", "name3": "cat"}
	// key
	fmt.Println("=========== for map key")
	for key := range name {
		fmt.Println(key)
	}
	// value
	fmt.Println("=========== for map value")
	for _,value := range name {
		fmt.Println(value)
	}
	// key & value
	fmt.Println("=========== for map key & value")
	for key,value := range name {
		fmt.Println(key,":",value)
	}
}

$ go run map.go
=========== for map key
name3
name1
name2
=========== for map value
adou
menghu
cat
=========== for map key & value
name1 : adou
name2 : menghu
name3 : cat

array

package main

import "fmt"

func main()  {
	fmt.Println("=========== index 遍历数组")
	arr := [...]int{6,2,4,9,8,3}
	for i:= 0;i<len(arr);i++{
		fmt.Print(arr[i],"\n")
	}
	fmt.Println("=========== range 遍历数组")
	sum := 0
	for _, value := range arr{
		//fmt.Println(index, "\t",value)
		fmt.Println(value)
		sum += value
	}
	fmt.Println("sum:",sum)
}

$ go run array.go 
=========== index 遍历数组
6
2
4
9
8
3
=========== range 遍历数组
6
2
4
9
8
3
sum: 32

slice

package main
import (
	"fmt"
)
func main() {
	person := [] string {"Tom", "Aaron", "John"}
	fmt.Printf("len=%d cap=%d slice=%v\n", len(person), cap(person), person)
	fmt.Println("")
	//循环 key value
	for k, v := range person {
		fmt.Printf("person[%d]: %s\n", k, v)
	}
	fmt.Println("")
	for i := range person {
		fmt.Printf("person[%d]: %s\n", i, person[i])
	}
	fmt.Println("")
	for i := 0; i < len(person); i++ {
		fmt.Printf("person[%d]: %s\n", i, person[i])
	}
	fmt.Println("")
	//使用空白符
	for _, name := range person {
		fmt.Println("name :", name)
	}
}
$ go run slice.go 
len=3 cap=3 slice=[Tom Aaron John]

person[0]: Tom
person[1]: Aaron
person[2]: John

person[0]: Tom
person[1]: Aaron
person[2]: John

person[0]: Tom
person[1]: Aaron
person[2]: John

name : Tom
name : Aaron
name : John