• GO-map数据结构


    一、map简介

    key - value 的数据结构,又叫字典或者关联数组

    1、声明(声明是不会分配内存,初始化用make)

    var map1 map[key type] value type

    var a map[string]string

    var a map[string]int

    var a map[int]string

    var a map[string] map[string]string

    2、map相关操作

    func testMap(){
        var a map[string]string
        a = make(map[string]string,10)
        a["hello"] = "world" //插入和更新操作
        a["hello2"] = "world2" //插入和更新操作
        Val,ok := a["hello"] //查找
        if ok {
            for k,v := range a {
                fmt.Println(k,v)
            }
        }
        delete(a,"hello") //删除
        fmt.Println(a,Val,ok)
        fmt.Println(a["hello"])
        fmt.Println(len(a)) //长度
    }
     
    3、map是引用类型
    func modify(a map[string]string)map[string]string{
        a["hello2"] = "hello bin change"
        return a
    }
     
    4、slice of map切片中包含字典
    func sliceOfMap(){
        items := make([]map[int]int,5)
        for i := 0;i<5;i++{
            items[i] = make(map[int]int)
        }
        fmt.Println(items)
    }
     
    5、map排序
    a、先获取所有key,把key进行排序
    b、按照排序好的key,进行遍历
    示例:
    func testMap2(){
        var a map[string]string

        a = make(map[string]string,10)
        a["hello"] = "world" //插入和更新操作
        a["hello3"] = "world3" //插入和更新操作
        a["hello2"] = "world2" //插入和更新操作
        fmt.Println(a)
        var keys []string


        for k,v := range a {
            fmt.Printf("a[%s] = %s ",k,v)
            keys = append(keys,k)
        }
        fmt.Println(" ")
        sort.Strings(keys) //对key进行排序
        for _,k := range keys {
            fmt.Printf("a[%s] = %s ",k,a[k])
        }
    }
     
    6、map反转
    初始化另外一个map,把key和value互换即可
     示例:
    func testMap3(){
        var a map[string]string
        var b map[string]string

        a = make(map[string]string,10)
        b = make(map[string]string,10)
        a["hello"] = "world" //插入和更新操作
        a["hello3"] = "world3" //插入和更新操作
        a["hello2"] = "world2" //插入和更新操作
        for k,v :=range a {
            b[v] = k
        }
        fmt.Println(a)
        fmt.Println(b)
    }
     
     
     
  • 相关阅读:
    报错:maven 程序包org.junit不存在
    Sublime Text 3
    Win10使用技巧
    CookieHelper
    log4net
    文件导出 Aspose
    C# 数字证书加载 X509Certificate2
    前后端文件上传
    WebApi 后端文件传输至远程服务器
    aspnet_regiis.exe用法(备忘非自创)
  • 原文地址:https://www.cnblogs.com/willpower-chen/p/8073858.html
Copyright © 2020-2023  润新知