为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
喵喵时光机 2022-10-24 09:28:21
我编写了下面的代码来检测结果是否有超过 1 个具有价值的 SomeStruct,如果只有一个则返回 AnotherStruct.ID。通常结果只有一个 SomeStruct 有值,其余的都是空的,然后我会得到 AnotherStruct 的 id。您可能会在下面阅读我的逻辑,逻辑是正确的,但对我来说看起来很难看,有没有更好的方法来写这个?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 {    return tmp[0], nil}
查看完整描述

3 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

您所要做的就是存储来自另一个结构的 ID 并确保您的 ID 不超过 1。


这是对@S4eed3sm 答案的扩展:


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


查看完整回答
反对 回复 2022-10-24
?
倚天杖

TA贡献1828条经验 获得超3个赞

您不需要将 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


查看完整回答
反对 回复 2022-10-24
?
子衿沉夜

TA贡献1828条经验 获得超3个赞

我不完全理解你的逻辑和用例,但最后一个 else 是多余的而不是惯用的。


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


查看完整回答
反对 回复 2022-10-24
  • 3 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号