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 关注
- 93 浏览
添加回答
举报