How to find out element position in slice?

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

    I had the same issue few months ago and I solved in two ways:

    First method:

    func Find(slice interface{}, f func(value interface{}) bool) int {
        s := reflect.ValueOf(slice)
        if s.Kind() == reflect.Slice {
            for index := 0; index < s.Len(); index++ {
                if f(s.Index(index).Interface()) {
                    return index
                }
            }
        }
        return -1
    }
    

    Use example:

    type UserInfo struct {
        UserId          int
    }
    
    func main() {
        var (
            destinationList []UserInfo
            userId      int = 123
        )
        
        destinationList = append(destinationList, UserInfo { 
            UserId          : 23,
        }) 
        destinationList = append(destinationList, UserInfo { 
            UserId          : 12,
        }) 
        
        idx := Find(destinationList, func(value interface{}) bool {
            return value.(UserInfo).UserId == userId
        })
        
        if idx < 0 {
            fmt.Println("not found")
        } else {
            fmt.Println(idx)    
        }
    }
    

    Second method with less computational cost:

    func Search(length int, f func(index int) bool) int {
        for index := 0; index < length; index++ {
            if f(index) {
                return index
            }
        }
        return -1
    }
    

    Use example:

    type UserInfo struct {
        UserId          int
    }
    
    func main() {
        var (
            destinationList []UserInfo
            userId      int = 123
        )
        
        destinationList = append(destinationList, UserInfo { 
            UserId          : 23,
        }) 
        destinationList = append(destinationList, UserInfo { 
            UserId          : 123,
        }) 
        
        idx := Search(len(destinationList), func(index int) bool {
            return destinationList[index].UserId == userId
        })
        
        if  idx < 0 {
            fmt.Println("not found")
        } else {
            fmt.Println(idx)    
        }
    }
    

提交回复
热议问题