How to find out element position in slice?

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

    You could write a function;

    func indexOf(element string, data []string) (int) {
       for k, v := range data {
           if element == v {
               return k
           }
       }
       return -1    //not found.
    }
    

    This returns the index of a character/string if it matches the element. If its not found, returns a -1.

提交回复
热议问题