Существует ли способ проверить части/карты на присутствие значения?
Я хотел бы добавить значение к части, только если это не существует в части.
Это работает, но это кажется подробным. Существует ли лучший способ сделать это?
orgSlice := []int{1, 2, 3}
newSlice := []int{}
newInt := 2
newSlice = append(newSlice, newInt)
for _, v := range orgSlice {
if v != newInt {
newSlice = append(newSlice, v)
}
}
newSlice == [2 1 3]
package main
import (
"fmt"
"os"
"reflect"
)
func main() {
/* s := []string{"a", "b"}
fmt.Println(s)
s = AppendIfMissing(s, "4").([]string)
fmt.Println(s)*/
/* var a []*string
a = make([]*string, 0)
e := "4"
a = AppendIfMissing(a, &e).([]*string)
fmt.Println(*a[0])*/
var a []*float64
a = make([]*float64, 3)
e := 4.4
d := 4.41
a = AppendIfMissing(a, &e).([]*float64)
a = AppendIfMissing(a, &d).([]*float64)
fmt.Println(*a[3], *a[4])
}
func AppendIfMissing(array interface{}, element interface{}) interface{} {
if reflect.ValueOf(array).IsNil() {
fmt.Fprintf(os.Stderr, "array not initialized\n")
return nil
}
switch reflect.TypeOf(array).Kind() {
case reflect.Slice:
arrayV := reflect.ValueOf(array)
arrayVLen := arrayV.Len()
if arrayVLen == 0 {//if make len == 0
sliceNew := reflect.MakeSlice(reflect.ValueOf(array).Type(), 1, 1)
if sliceNew.Index(0).Type() != reflect.ValueOf(element).Type() {
fmt.Fprintf(os.Stderr, "types are not same\n")
return sliceNew.Interface()
}
sliceNew.Index(0).Set(reflect.ValueOf(element))
return sliceNew.Interface()
}
for i := 0; i < arrayVLen; i++ {
if i == 0 && reflect.ValueOf(element).Kind() != arrayV.Index(i).Kind() {
fmt.Fprintf(os.Stderr, "types are not same\n")
return array
}
if arrayV.Index(i).Interface() == element {
return array
}
}
default:
fmt.Fprintf(os.Stderr, "first element is not array\n")
return array
}
arrayV := reflect.ValueOf(array)
elementV := reflect.ValueOf(element)
appendAE := reflect.Append(arrayV, elementV)
return appendAE.Interface()
}