3 回答

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

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

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
- 3 回答
- 0 關注
- 115 瀏覽
添加回答
舉報