以下内容转载自 https://blog.csdn.net/weixin_37998647/article/details/78592964
一、遍历结构体字段:
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{ // range会保证从头到尾
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])
}
}