douxun3496 2018-06-04 18:47
浏览 70

Golang通用Hashmap

I'm trying to make a wrapper in go for the map[] type so that I can add some methods like contains() (this almost makes me miss java). However, I don't know how I can do anything like generics in java.

While almost everything I've read says that golang doesn't have generic types, there must be a better way than writing a separate struct for every single possible combination of structs and values that I'm using.

Here's what I'm trying to do, even though the code doesn't work:

func newMap(key interface{}, val interface{}) {
    keytype := key.(type)
    valtype := val.(type)

    return hashmap{map[keytype]valtype}
}

type hashmap struct {
    hashmap     map[]
}

Any help/explanation on how to do this would be appreciated.

EDIT: Contains isn't the only thing I'm trying to replicate, hence the desire to make a "generic" hashmap. replace(), isEmpty(), all that fun stuff as well.

  • 写回答

2条回答 默认 最新

  • douna1895 2018-06-04 18:58
    关注

    Golang does not have generics, as you say.

    But the maps can be declared using your own types, so you don't necessarily need to write your own "generic" hashmap to use things like "contains" or "is empty".

    Example (assuming some Icon and Colour types already exist, as well as the GetTheIcon function that returns some icon):

    // this one will map Icon -> Colour
    iconToColours := make(map[Icon]Colour)
    
    myIcon := GetTheIcon()
    // second return argument is true if the key was found in the map
    _, iconIsContained := iconToColours[myIcon]
    
    // check if the map is empty
    isEmpty := (len(iconToColours) == 0)
    

    See more here:

    https://blog.golang.org/go-maps-in-action

    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用