包含切片的方法 [英] Contains method for a slice

查看:111
本文介绍了包含切片的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中有没有类似于 slice.contains(object)方法的东西,而不必通过切片中的每个元素进行搜索?

解决方案

Mostafa已经指出这样的方法是微不足道的,而mkb给了你一个暗示使用二分查找从排序包。但是如果你打算做很多这样的包含检查,你也可以考虑使用地图。



通过使用检查特定映射关键字是否存在是很简单的值,ok:= yourmap [key] idiom。由于您对该值不感兴趣,因此您可能还会创建一个 map [string] struct {} 。在这里使用空的 struct {} 具有的优点是它不需要任何额外的空间,Go的内部映射类型针对这种类型的值进行了优化。因此,在Go世界中, map [string] struct {} 是流行的选择。


Is there anything similar to a slice.contains(object) method in Go without having to do a search through each element in a slice?

解决方案

Mostafa has already pointed out that such a method is trivial to write, and mkb gave you a hint to use the binary search from the sort package. But if you are going to do a lot of such contains checks, you might also consider using a map instead.

It's trivial to check if a specific map key exists by using the value, ok := yourmap[key] idiom. Since you aren't interested in the value, you might also create a map[string]struct{} for example. Using an empty struct{} here has the advantage that it doesn't require any additional space and Go's internal map type is optimized for that kind of values. Therefore, map[string] struct{} is a popular choice for sets in the Go world.

这篇关于包含切片的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆