go遍歷結構體(struct)欄位對應的值,切片(slice),字典(map)
阿新 • • 發佈:2019-02-17
一、遍歷結構體欄位:
eg1:
package main
import (
"fmt"
"reflect"
)
type person struct {
name string
age int
}
func main() {
v := reflect.ValueOf(person{"steve", 30})
count := v.NumField()
for i := 0; i < count; i++ {
f := v.Field(i)
switch f.Kind() {
case reflect.String:
fmt.Println(f.String())
case reflect.Int:
fmt.Println(f.Int())
}
}
}
輸出結果:
steve
30
eg2:
package main
import (
"fmt"
"reflect"
)
type NotknownType struct {
s1, s2, s3 string
}
var secret interface{} = NotknownType{"Ada", "Go" , "Oberon"}
func main() {
value := reflect.ValueOf(secret)
for i := 0; i < value.NumField(); i++ {
fmt.Printf("Field %d: %v\n", i, value.Field(i))
}
}
輸出結果:
Field 0: Ada
Field 1: Go
Field 2: Oberon
二、遍歷切片:
for range 結構
package main
import (
"fmt"
)
func main(){
slice := []string {"hello","world","hello","everyone!"}
for k,val:=range slice{
fmt.Printf("slice %d is :%s\n",k,val )
}
}
輸出結果:
slice 0 is :hello
slice 1 is :world
slice 2 is :hello
slice 3 is :everyone!
三、遍歷map:
package main
import (
"fmt"
)
func main() {
m := make(map[string]string)
m["1"] = "hello"
m["2"] = "world"
m["3"] = "go"
m["4"] = "is"
m["5"] = "cool"
fmt.Printf("The corresponding relationship between key and value is:\n")
for key, val := range m {
fmt.Printf("%v===>%v\n", key, val)
}
}
輸出結果:
The corresponding relationship between key and value is:
1===>hello
2===>world
3===>go
4===>is
5===>cool
但是還有一個問題,上面的程式不做改動執行第二次,結果順序就會改變,因為map遍歷出來結果是無序的,這不好控制,也不利於業務邏輯;當業務依賴key次序時,需要引入“sort”包來解決隨機化問題
程式碼如下:
package main
import (
"fmt"
"sort"
)
func main() {
m := make(map[string]string)
m["1"] = "hello"
m["2"] = "world"
m["3"] = "go"
m["4"] = "is"
m["5"] = "cool"
sorted_keys := make([]string, 0)
for k, _ := range m {
sorted_keys = append(sorted_keys, k)
}
sort.Strings(sorted_keys)
for _, k := range sorted_keys {
fmt.Printf("%v=====>%v\n", k, m[k])
}
}
輸出結果是:
1=====>hello
2=====>world
3=====>go
4=====>is
5=====>cool
注意:
輸出的結果執行多次不會改變順序。
但是key的先後順序是按照字母或者數字排列的。