How to find out element position in slice?

前端 未结 7 765
无人及你
无人及你 2020-12-07 11:20

How does one determine the position of an element present in slice?

I need something like the following:

type intSlice []int

func (slice intSlice) p         


        
相关标签:
7条回答
  • 2020-12-07 11:49

    Another option is to sort the slice using the sort package, then search for the thing you are looking for:

    package main
    
    import (
        "sort"
        "log"
        )
    
    var ints = [...]int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}
    
    func main() {
            data := ints
            a := sort.IntSlice(data[0:])
            sort.Sort(a)
            pos := sort.SearchInts(a, -784)
            log.Println("Sorted: ", a)
            log.Println("Found at index ", pos)
    }
    

    prints

    2009/11/10 23:00:00 Sorted:  [-5467984 -784 0 0 42 59 74 238 905 959 7586 7586 9845]
    2009/11/10 23:00:00 Found at index  1
    

    This works for the basic types and you can always implement the sort interface for your own type if you need to work on a slice of other things. See http://golang.org/pkg/sort

    Depends on what you are doing though.

    0 讨论(0)
提交回复
热议问题