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
Subtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time.
Creating a Function in Golang
How to concatenate two or more slices in Golang?
Example to use Weekday and YearDay function
How to trim leading and trailing white spaces of a string in Golang?
How to check if a string contains a numbers in Golang?
How to check lowercase characters in a string in Golang?
How to check if a string contains a white space in Golang?
How to use for and foreach loop?
Functions mess (recursive anonymous function) in Golang