亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號