Home > Software design >  Golang: map with multiple values per key
Golang: map with multiple values per key

Time:05-16


 func ParseportsFromFile(file string) (map[string]string, error) {
            buf, err := ioutil.ReadFile(file)
            if err != nil {
                return nil, err
            }
            ret := [make(map[string]string)]
            rows := strings.Split(string(buf), "\n")
            for _, row := range rows {
                kvs := strings.SplitN(row, "=", 2)
                if len(kvs) == 2 {
                    ret[strings.TrimSpace(kvs[0])] = strings.TrimSpace(kvs[1])
                }
            }
            return ret, nil
        }

This function allows me to read a file like that :

user1=123 
user1=321 
user2=124 

However, the data return is

map[user1:321 user2:124]

So that mean user1=123 has been overwritten with user1=321 How to avoid that ? How to create an array like map[user1:[123,321], user2: 124] to avoid an item to overwrite another ?

CodePudding user response:

Since go is strongly typed, it would be easier to make it right away a map of slices. See the http.Header type, for example. They had the same problem to solve when designing it.

In your case, this could look something like this:

result := make(map[string][]string)

for _, row := range rows {
    parts := strings.Split(row, "=")
    key := parts[0]
    value := parts[1]
    result[key] = append(result[key], value)
}

https://go.dev/play/p/5uRH-aQmATR

Otherwise, you need to use interface{} (any) so you can have both, string and []string, but the logic to get that done would be more complex, and using it would be also more complex since you always need to check what it is and do type assertion and so on. After all, I would not recommend it.

  • Related