Ho to remove a value of a key in a map?

Issue

I have a a map which has a key and multiple values for that key.

What i want to do is delete a single value from values.

Example:

map1 := make(map[string][]string)
str1 := []string{"Jon", "Doe", "Captain", "America"}
str2 := "Doe"
map1["p1"] = str1

In the above example I want to remove value form the "p1" if it is present in str2, in my case it is "Doe"

after removing the value map should be like this
p1:[Jon Captain America]

Is this possible or do i have to rewrite the whole map again?

Solution

It’s not possible to "in place" delete an element from a slice that’s inside a map. You need to first get the slice from the map, delete the element from the slice, and then store the result of that in the map.

For finding the element’s index by its value and then deleting it from the slice you can use the golang.org/x/exp/slices package if you are using Go1.18.

package main

import (
    "fmt"

    "golang.org/x/exp/slices"
)

func main() {
    map1 := make(map[string][]string)
    str1 := []string{"Jon", "Doe", "Captain", "America"}
    str2 := "Doe"
    map1["p1"] = str1

    idx := slices.Index(map1["p1"], str2)
    map1["p1"] = slices.Delete(map1["p1"], idx, idx+1)

    fmt.Println(map1)
}

https://go.dev/play/p/EDTGAJT-VdM

Answered By – mkopriva

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.