Contains method for a slice

2019-03-07 20:10发布

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

标签: go slice
8条回答
手持菜刀,她持情操
2楼-- · 2019-03-07 20:57

If it is not feasable to use a map for finding items based on a key, you can consider the goderive tool. Goderive generates a type specific implementation of a contains method, making your code both readable and efficient.

Example;

type Foo struct {
    Field1 string
    Field2 int
} 

func Test(m Foo) bool {
     var allItems []Foo
     return deriveContainsFoo(allItems, m)
}

To generate the deriveContainsFoo method:

  • Install goderive with go get -u github.com/awalterschulze/goderive
  • Run goderive ./... in your workspace folder

This method will be generated for deriveContains:

func deriveContainsFoo(list []Foo, item Foo) bool {
    for _, v := range list {
        if v == item {
            return true
        }
    }
    return false
}

Goderive has support for quite some other useful helper methods to apply a functional programming style in go.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-03-07 20:59

No, such method does not exist, but is trivial to write:

func contains(s []int, e int) bool {
    for _, a := range s {
        if a == e {
            return true
        }
    }
    return false
}

You can use a map if that lookup is an important part of your code, but maps have cost too.

查看更多
登录 后发表回答