Find element in a slice and move it to first position?
Example
package main
import (
"fmt"
)
func main() {
sliceInt := []int{11,2, 19, 220, 31, 5, 65, 70, 100}
find:=65
fmt.Println(sliceInt)
if len((sliceInt)) == 0 || (sliceInt)[0] == find {
fmt.Println(sliceInt)
return
}
if (sliceInt)[len(sliceInt)-1] == find {
(sliceInt) = append([]int{find}, (sliceInt)[:len(sliceInt)-1]...)
fmt.Println(sliceInt)
return
}
for p, x := range sliceInt {
if x == find {
(sliceInt) = append([]int{find}, append((sliceInt)[:p], (sliceInt)[p+1:]...)...)
break
}
}
fmt.Println(sliceInt)
}
Output
[11 2 19 220 31 5 65 70 100]
[65 11 2 19 220 31 5 70 100]
Most Helpful This Week
Regular expression to extract text between square brackets
Example: Fields and FieldsFunc from BYTES Package
Get Year, Month, Day, Hour, Min and Second from current date and time.
How to use array in Go Programming Language?
How to check if a string contains a substring in Golang?
How to declare empty Map in Go?
How to read/write from/to file in Golang?
How to blur an image in Golang?
How to check if a string contains certain characters in Golang?
Golang String Concatenation