欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Go遍历struct,map,slice的实现

程序员文章站 2022-04-18 17:17:33
遍历结构体如何实现遍历结构体字段? 好吧,言归正传!举个例子:demo1:package mainimport ( "fmt" "reflect")type student struc...

遍历结构体

如何实现遍历结构体字段? 好吧,言归正传!举个例子:

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:    "mahuateng@qq.com",
        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内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!