当前位置: > > > > Golang如何美化搜索唯一id逻辑
来源:stackoverflow
2024-05-01 11:51:30
0浏览
收藏
各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题是《Golang如何美化搜索唯一id逻辑》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!
问题内容
我编写了下面的代码来检测结果是否有超过 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 }
正确答案
您所要做的就是存储来自其他结构的 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
我不完全理解你的逻辑和用例,但最后一个 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
终于介绍完啦!小伙伴们,这篇关于《Golang如何美化搜索唯一id逻辑》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~公众号也会发布Golang相关知识,快来关注吧!