How to find out element position in slice?
The Sort function sorts the data interface in both ascending and descending order. IntSlice attaches the methods of Interface to []int, sorting in increasing order. StringSlice attaches the methods of Interface to []string, sorting in increasing order.
Below is an example to search particular string or integer in string or integer slice vice versa.
Example
package main
import (
"fmt"
"sort"
)
func main() {
str := []string{"Washington","Texas","Ohio","Nevada","Montana","Indiana","Alaska"} // unsorted
sort.Sort(sort.StringSlice(str))
fmt.Println(str) // sorted
fmt.Println("Length of Slice: ", sort.StringSlice.Len(str)) // 7
fmt.Println("OHIO found in Slice at position: ", sort.StringSlice(str).Search("OHIO")) // 4
fmt.Println("Ohio found in Slice at position: ", sort.StringSlice(str).Search("Ohio")) // 4
fmt.Println("ohio found in Slice at position: ", sort.StringSlice(str).Search("ohio")) // 7
fmt.Println("\n\n")
num := []int{9, 22, 54, 33, -10, 40} // unsorted
sort.Sort(sort.IntSlice(num))
fmt.Println(num) // sorted
fmt.Println("Length of Slice: ", sort.IntSlice.Len(num)) // 6
fmt.Println("40 found in Slice at position: ", sort.IntSlice(num).Search(40)) // 4
fmt.Println("82 found in Slice at position: ", sort.IntSlice(num).Search(82)) // 6
}
Output
[Alaska Indiana Montana Nevada Ohio Texas Washington]
Length of Slice: 7
OHIO found in Slice at position: 4
Ohio found in Slice at position: 4
ohio found in Slice at position: 7
[-10 9 22 33 40 54]
Length of Slice: 6
40 found in Slice at position: 4
82 found in Slice at position: 6
Most Helpful This Week
How to check string contains uppercase lowercase character in Golang?
How to remove symbols from a string in Golang?
How to wait for Goroutines to Finish Execution?
How to add Watermark or Merge two image?
Higher Order Functions in Golang
Regular expression to validate the date format in "dd/mm/yyyy"