8

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?

2 Answers 2

9

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) 
   ...
}
0
3

Starting with Go 1.18 you can now use netip.Addr directly as map key. One of the declared intents of this new IP type is exactly to support == and != operators, therefore allowing usage as map keys.

Addr represents an IPv4 or IPv6 address (with or without a scoped addressing zone), similar to net.IP or net.IPAddr.

Unlike net.IP or net.IPAddr, Addr is a comparable value type (it supports == and can be a map key) and is immutable.

So now you can declare your struct field as:

MapOfValues map[netip.Addr]chan string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.