Home > Back-end >  Ho to remove a value of a key in a map?
Ho to remove a value of a key in a map?

Time:03-26

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?

CodePudding user response:

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

CodePudding user response:

package main

func main () {
    var sessions = map[string] chan int{};
    delete(sessions, "moo");
}

or

package main

func main () {
    var sessions = map[string] chan int{};
    sessions["moo"] = make (chan int);
    _, ok := sessions["moo"];
    if ok {
        delete(sessions, "moo");
    }
}
  •  Tags:  
  • go
  • Related