'How to delete an element from a slice that's inside a map?
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 1:[1]
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)
}
Solution 2:[2]
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");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Areg Nikoghosyan |
