Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

net.IP as map key type in golang?

Tags:

go

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?

like image 622
Ronin Goda Avatar asked May 19 '18 15:05

Ronin Goda


People also ask

How do you create a map in Golang?

There's no specific data type in Golang called map; instead, we use the map keyword to create a map with keys of a certain type, and values of another type (or the same type). In this example, we declare a map that has string s for its keys, and float64 s for its values.

What data types can be used as keys in Golang maps?

In maps, most of the data types can be used as a key like int, string, float64, rune, etc. Maps also allow structs to be used as keys. These structs should be compared with each other. A structure or struct in Golang is a user-defined type that allows to combine fields of different types into a single type. Example of a struct:

What is a struct in Golang?

A structure or struct in Golang is a user-defined type that allows to combine fields of different types into a single type. Let’s see how to implement a struct in a map: Iterating over a map: You can also run a loop to access and operate each map key individually.

How to delete a struct key from the map in Golang?

Deleting a struct key from the map: You can delete a struct key from the map using the delete () function. It is an inbuilt function and does not return any value and does not do anything if the key does not present in the given map. The syntax for the same is as follows:


1 Answers

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) 
   ...
}
like image 175
Bayta Darell Avatar answered Oct 25 '22 02:10

Bayta Darell