Go: Append if unique

后端 未结 4 1603
深忆病人
深忆病人 2021-01-30 06:28

Is there a way to check slices/maps for the presence of a value?

I would like to add a value to a slice only if it does not

4条回答
  •  既然无缘
    2021-01-30 06:55

    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()
    }
    

提交回复
热议问题