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
Copy an array by value and reference into another array
Golang Functions Returning Multiple Values
How to write backslash in Golang string?
Create and Print Multi Dimensional Slice in Golang
Regular expression to extract domain from URL
Regular expression to validate email address
Golang Convert String into Snake Case
How to use for and foreach loop?
How to use a mutex to define critical sections of code and fix race conditions?
Regular expression to validate phone number