登录
首页 >  Golang >  Go教程

Go遍历struct,map,slice的实现

来源:脚本之家

时间:2023-01-07 12:07:16 303浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《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 

再举给栗子:

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 

输出:

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的实现》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表