Go: Append if unique

后端 未结 4 1639
深忆病人
深忆病人 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:45

    distincting a array of a struct :

    func distinctObjects(objs []ObjectType) (distinctedObjs [] ObjectType){
            var output []ObjectType
        for i:= range objs{
            if output==nil || len(output)==0{
                output=append(output,objs[i])
            } else {
                founded:=false
                for j:= range output{
                        if output[j].fieldname1==objs[i].fieldname1 && output[j].fieldname2==objs[i].fieldname2 &&......... {
                        founded=true
                    }
                }
                if !founded{
                    output=append(output,objs[i])
                }
            }
        }
        return output
    }
    

    where the struct here is something like :

    type ObjectType struct {
        fieldname1 string
        fieldname2 string
        .........
    }
    

    the object will distinct by checked fields here :

    if output[j].fieldname1==objs[i].fieldname1 && output[j].fieldname2==objs[i].fieldname2 &&......... {
    

提交回复
热议问题