简体   繁体   中英

Container types in Go

I am trying to familiarize myself with Go and so was trying to implements some search function but looking through the docs for the container types, none of the inbuilt type implements a contains method. Am i missing something and if not how do i go about testing for membership? Do I have to implement my own method or i have to iterate through all elements. If this is so what is the rationale behind the omission of this elementary method for container types?

The standard library's container types require you do type assertions when pulling elements out. The containers themselves have no way of doing tests for membership because they don't know the types they're containing and have no way of doing a comparison.

Ric Szopa's skip list implementation might be what you're looking for. It has a Set type which implements a Contains method.

https://github.com/ryszard/goskiplist

I've been using it in production and am quite happy with it.

Maps are a built-in type which has a "contains" construct, not a method, though.

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)
}

With the container/list package, you write your own loop to search for things. The reasoning for not having this provided in the package is probably as Dystroy said, that would hide an O(n) operation.

You can't add a method, so you just write a loop.

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

It's simple enough and the O(n) complexity is obvious.

In your review of data structures supplied with Go that support searching, don't miss the sort package. Functions there allow a slice to be sorted in O(n log(n)) and then binary searched in O(log(n)) time.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM