GO 遍历 结构体


结构体需要赋值 又不想一个个字段的写 可用结构体遍历赋值
遍历结构体字段
package main
import (
    "fmt"
    "reflect"
)
type User struct  {
    Id int
    Name string
    addr string
}
func main(){
    u := User{Id:1001, Name:"xxx" , addr:"yyy"}
    t := reflect.TypeOf(u)
    v := reflect.ValueOf(u)
    for k := 0; k < t.NumFiled(); k++ {
    fmt.Printf("%s -- %v \n", t.Filed(k).Name, v.Field(k).Interface())   
    }
}
当结构体中含有非导出字段 addr string 时 v.Field(k).Interface() 会 panic,注释addr string后正常

遍历切片

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 先后顺序 按照字母或者数字排列