doudiewen9435 2018-05-19 15:43
浏览 48
已采纳

net.IP作为golang中的映射密钥类型?

I have map with key as net.IP and value as a channel. But I'm getting a weird compile time error (invalid map key type)

17 type UdpServer struct {
18     ListenPort int
19
20     ConnRef *net.UDPConn
21     Log_ref *Logger
22     MapOfValues map[net.IP]chan string
23 }


$ go build c-manager.go
cmanager/c-udp_server.go:22:14: invalid map key type net.IP

$ go version
  go version go1.10.2 linux/amd64

What am I doing wrong? Can't we have net.IP as map key type?

  • 写回答

1条回答 默认 最新

  • dsuikgi9199 2018-05-19 16:02
    关注

    A net.IP is a slice type. Because slices are mutable, they cannot be used as map keys. Use a string as the key type:

    MapOfValues map[string]chan string
    

    Use a type conversion to convert from net.IP to string and back. Use IP.To16 to normalize addresses to the 16 byte representation.

    x.MapOfValues[string(ip.To16())] = v
    
    for k, v := range x.MapOfValues {
       ip := net.IP(k) // convert string to net.IP
       ...
    }
    

    If you want the keys to be printable, then use the IP.String and net.ParseIP functions to do the conversions:

    x.MapOfValues[ip.String()] = v
    
    for k, v := range x.MapOfValues {
       ip := net.ParseIP(k) 
       ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决