Home > Software engineering >  Golang how to beautify the search unique id logic
Golang how to beautify the search unique id logic

Time:12-30

I have written the below code to detect if the result has more than 1 SomeStruct that is having value, if only one then return the AnotherStruct.ID. Normally the result only have one SomeStruct that is having value, and the rest are empty, then I will get the id of AnotherStruct. You may read my logic below, the logic is correct, but it looks ugly to me, is there a better way to write this?

var tmp []string
for _, id := range result {
    if len(id.SomeStruct) > 0 {
        tmp = append(tmp, id.AnotherStruct.ID)
    }
}

if len(tmp) > 1 {
    return "Failure, ", fmt.Errorf("More than 1 id that has unique code")
} else {
    return tmp[0], nil
}

CodePudding user response:

You don't need to append ID to tmp slice, use a counter and check it inside the for, by this you have better performance. maybe this will help you:

    c := 0
    tmp := ""
    for _, id := range result {
        if len(id.SomeStruct) > 0 {
            c  
            if c > 1 {
                return "", fmt.Errorf("More than 1 id that has unique code")
            }
            tmp = id.AnotherStruct.ID
        }
    }
    return tmp, nil

I missed the tmp return value, thanks @stefan-zhelyazkov

CodePudding user response:

I don't fully understand your logic & use case, but the last else is redundant and not idiomatic.

var tmp []string
for _, id := range result {
    if len(id.SomeStruct) > 0 {
        tmp = append(tmp, id.AnotherStruct.ID)
    }
}

if len(tmp) > 1 {
    return "Failure, ", fmt.Errorf("More than 1 id that has unique code")
}
// else was redundant

return tmp[0], nil

CodePudding user response:

All you have to do is store the ID from the other struct and make sure that you don't have more than 1.

This is expanding on @S4eed3sm answer:

var tmp string
for _, o := range result {
    if len(o.SomeStruct) > 0 {
        if len(tmp) > 0 {
            return "Failure, ", fmt.Errorf("More than 1 id that has unique code")
        }
        tmp = o.AnotherStruct.ID
    }
}
return tmp, nil
  •  Tags:  
  • go
  • Related