zoukankan      html  css  js  c++  java
  • 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)
    }
     
     
     
  • 相关阅读:
    HTTP协议详解(真的很经典)
    几点建议,让Redis在你的系统中发挥更大作用
    Redis能干啥?细看11种Web应用场景
    Java中使用Jedis操作Redis
    java的锁机制——synchronized
    web开发中的两把锁之数据库锁:(高并发--乐观锁、悲观锁)
    一分钟教你知道乐观锁和悲观锁的区别
    $^,$@,$?,$<,$(@D),$(@F) of makefile
    linux shared lib 使用与编译
    makefile learning
  • 原文地址:https://www.cnblogs.com/willpower-chen/p/8073858.html
Copyright © 2011-2022 走看看