I am trying to use the slices package to delete a chan []byte
from a slice of them.
But I have a known value that I want to remove instead of using the position like it shows here How to delete an element from a Slice in Golang.
import "golang.org/x/exp/slices"
var receiverChannels []chan []byte
channel := make(chan []byte)
receiverChannels = append(receiverChannels, channel)
receiverChannels = slices.Delete(receiverChannels, channel)
CodePudding user response:
If the ordering of the slice is not important, you can use a map instead:
var receiverChannels = make(map[chan []byte]struct{})
channel:=make(chan []byte)
receiverChannels[channel]=struct{}{}
delete(receiverChannels,channel)
Otherwise, you need a find
helper function:
func find(channels []chan []byte, ch chan []byte) int {
for i:=range channels {
if channels[i]==ch {
return i
}
}
return -1
}
Or a generic find
:
func find[T comparable](slice []T, item T) int {
for i := range slice {
if slice[i] == item {
return i
}
}
return -1
}
If you need to keep a slice but ordering is not important, you can simply move the last element and truncate the slice:
i:=find(receiverChannels, channel)
if i!=-1 {
if i<len(receiverChannels)-1 {
receiverChannels[i]=receiverChannels[len(receiverChannels)-1]
}
receiverChannels=receiverChannels[:len(receiverChannels)-1]
}
Last, if ordering is important:
i:=find(receiverChannels, channel)
if i!=-1 {
receiverChannels=append(receiverChannels[:i], receiverChannels[i 1:]...)
receiverChannels=receiverChannels[:len(receiverChannels)-1]
}
CodePudding user response:
Delete(receiverChannels, channel)
func Delete[T comparable](collection []T, el T) []T {
idx := Find(collection, el)
if idx > -1 {
return slices.Delete(collection, idx, idx 1)
}
return collection
}
func Find[T comparable](collection []T, el T) int {
for i := range collection {
if collection[i] == el {
return i
}
}
return -1
}