Go遍歷struct,map,slice的實現

遍歷結構體

如何實現遍歷結構體字段? 好吧,言歸正傳!舉個例子:

demo1:

package main

import (
   "fmt"
   "reflect"
)

type Student struct {
   name string
   age  int
}

func main() {
   v := reflect.ValueOf(Student{"喬峰", 29})
   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())
      }
   }
}

再舉給栗子:

package main

import (
   "fmt"
   "reflect"
)

type LanType struct {
   s1, s2, s3 string
}

var language interface{} = LanType{"Php", "Go", "Python3"}

func main() {
   value := reflect.ValueOf(language)
   for i := 0; i < value.NumField(); i++ {
      fmt.Printf("字段索引 %d: %v\n", i, value.Field(i))
   }
}

輸出:

BASIC
字段索引 0: Php
字段索引 1: Go
字段索引 2: Python3

遍歷切片

使用 for range遍歷:

package main

import (
   "fmt"
)

func main() {
   language := []string{"Php", "Go", "Python3"}
   for k, val := range language {
      fmt.Printf("切片索引 %d is :%s\n", k, val)
   }
}

輸出:

BASIC
切片索引 0 is :Php
切片索引 1 is :Go
切片索引 2 is :Python3

遍歷Map

package main

import (
   "fmt"
)

func main() {
   language := make(map[string]string)
   language["1"] = "Php"
   language["2"] = "Go"
   language["3"] = "Python3"
   language["4"] = "C#"

   for key, val := range language {
      fmt.Printf("%v=>%v\n", key, val)
   }
}

輸出:這裡就不貼瞭,結果會隨機輸出,因為map遍歷出來結果是無序的,順序不好控制,也不利於業務邏輯;當業務依賴key次序時,那麼我們就需要引入“sort”包來解決隨機化問題:

比如這樣:

package main

import (
   "fmt"
   "sort"
)

func main() {
   language := make(map[string]string)
   language["1"] = "Php"
   language["2"] = "Go"
   language["3"] = "Python3"
   language["4"] = "C#"

   sorted_keys := make([]string, 0)
   for k, _ := range language {
      sorted_keys = append(sorted_keys, k) // 提取鍵名
   }
   sort.Strings(sorted_keys) //

   for _, k := range sorted_keys {
      fmt.Printf("%v=>%v\n", k, language[k])
   }
}

輸出:

BASIC
1=>Php
2=>Go
3=>Python3
4=>C#

這樣輸出的結果運行多次也不會改變順序。

Golang json序列化(struct,int,map,slice)

package main

import (
    "encoding/json"
    "fmt"
)

//把結構體都改小寫
type User struct {
    UserName string `json:"user_name"` //json的tag標記
    Nickname string `json:"nickname"`
    Age      int
    Birthday string
    Sex      string
    Email    string
    Phone    string
}

func testStruct() {
    user1 := &User{
        UserName: "超哥",
        Nickname: "大頭哥",
        Age:      18,
        Birthday: "2008/8/8",
        Sex:      "男",
        Email:    "[email protected]",
        Phone:    "110",
    }

    //開始json序列化
    data, err := json.Marshal(user1)
    if err != nil {
        fmt.Printf("json.marshal failed,err:", err)
        return
    }
    fmt.Printf("%s\n", string(data))
}

func testInt() {
    var a = 18
    //開始json序列化
    data, err := json.Marshal(a)
    if err != nil {
        fmt.Printf("json.marshal failed,err:", err)
        return
    }
    fmt.Printf("%s\n", string(data))

}

func testMap() {
    var m map[string]interface{}     //聲明map
    m = make(map[string]interface{}) //必須初始化map分配內存
    m["username"] = "user1"
    m["age"] = 18
    m["sex"] = "man"
    fmt.Println(m)
    data, err := json.Marshal(m)
    if err != nil {
        fmt.Printf("json.marshal failed,err:", err)
        return
    }
    fmt.Printf("%s\n", string(data))

}

func testSlice() {
    //定義一個slice,元素是map
    var m map[string]interface{}
    var s []map[string]interface{}
    m = make(map[string]interface{})
    m["username"] = "user1"
    m["age"] = 18
    m["sex"] = "man"
    s = append(s, m)
    m = make(map[string]interface{})
    m["username"]="user2"
    m["age"]=188
    m["sex"]="male"
    s=append(s,m)
    data, err := json.Marshal(s)
    if err != nil {
        fmt.Printf("json.marshal failed,err:", err)
        return
    }
    fmt.Printf("%s\n", string(data))

}
func main() {
    testStruct() //結構體的序列化
    testInt()//序列化數值
    testMap()//序列化map
    testSlice()//序列化切片
}

到此這篇關於Go遍歷struct,map,slice的實現的文章就介紹到這瞭,更多相關Go遍歷struct,map,slice內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: