How to find out element position in slice?

前端 未结 7 763
无人及你
无人及你 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:37

    You can create generic function in idiomatic go way:

    func SliceIndex(limit int, predicate func(i int) bool) int {
        for i := 0; i < limit; i++ {
            if predicate(i) {
                return i
            }
        }
        return -1
    }
    

    And usage:

    xs := []int{2, 4, 6, 8}
    ys := []string{"C", "B", "K", "A"}
    fmt.Println(
        SliceIndex(len(xs), func(i int) bool { return xs[i] == 5 }),
        SliceIndex(len(xs), func(i int) bool { return xs[i] == 6 }),
        SliceIndex(len(ys), func(i int) bool { return ys[i] == "Z" }),
        SliceIndex(len(ys), func(i int) bool { return ys[i] == "A" }))
    

提交回复
热议问题