Container Types in Go

I am trying to get to know Go and therefore trying to implement some search function, but while looking through documents for container types, none of the built-in types implement the contains method. I'm missing something, but if not, how do I get tested for membership? Should I implement my own method, or should I iterate over all the elements. If so, what is the reason for the lack of this elementary method for container types?

+7
source share
3 answers

The standard library container types require you to make type statements when pulling items. The containers themselves are not able to run tests for membership because they do not know the types that they contain and are not able to make comparisons.

Implementing a Ric Szopa exclusion list may be what you are looking for. It is of type Set, which implements the Contains method.

https://github.com/ryszard/goskiplist

I use it in production and am very pleased with it.

+7
source

Cards are a built-in type that has a "contains" construct, not a method.

http://play.golang.org/p/ddpmiskxqS

 package main import ( "fmt" ) func main() { a := map[string]string{"foo": "bar"} _, k := a["asd"] fmt.Println(k) _, k = a["foo"] fmt.Println(k) } 
+4
source

With the container / list package, you write your own loop for finding things. The reason this is not provided in the package is probably because Dystroy, who will hide the O (n) operation, said.

You cannot add a method, so you are just writing a loop.

 for e := l.Front(); e != nil; e = e.Next() { data := e.Value.(dataType) // type assertion if /* test on data */ { // do something break } } 

This is simple enough and the complexity of O (n) is obvious.

In the overview of data structures that come with Go that support search, don't miss the sort package. The functions there allow you to sort the slice in O (n log (n)), and then binary search in O (log (n)) time.

Finally, as Daniel suggested, consider third-party packages. There are several popular and mature packages for container types.

+3
source

All Articles