猿问

Golang如何美化搜索唯一id逻辑

我编写了下面的代码来检测结果是否有超过 1 个具有价值的 SomeStruct,如果只有一个则返回 AnotherStruct.ID。通常结果只有一个 SomeStruct 有值,其余的都是空的,然后我会得到 AnotherStruct 的 id。您可能会在下面阅读我的逻辑,逻辑是正确的,但对我来说看起来很难看,有没有更好的方法来写这个?


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

}


喵喵时光机
浏览 94回答 3
3回答

GCT1015

您所要做的就是存储来自另一个结构的 ID 并确保您的 ID 不超过 1。这是对@S4eed3sm 答案的扩展:var tmp stringfor _, 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

倚天杖

您不需要将 ID 附加到 tmp 切片,使用计数器并在 for 中检查它,这样您可以获得更好的性能。也许这会帮助你:    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我错过了 tmp 返回值,谢谢@stefan-zhelyazkov

子衿沉夜

我不完全理解你的逻辑和用例,但最后一个 else 是多余的而不是惯用的。var tmp []stringfor _, 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 redundantreturn tmp[0], nil
随时随地看视频慕课网APP

相关分类

Go
我要回答