sliceUnshift.go
· 453 B · Go
Sin formato
package main
import (
"fmt"
"slices"
)
func main() {
slc := []string{"a","b","c","d","e","f","g","h"}
itemsToPush := []string{"d","g"}
fmt.Println(slc)
for i, s := range slc {
// Move "d" and "g" to the start of slc
// The order of moved items will be reversed
if slices.Contains(itemsToPush, s) {
tmp := []string{s}
for ii:=i; ii > 0; ii-- {
slc[ii] = slc[ii-1]
}
slc = append(tmp, slc[1:]...)
}
}
fmt.Println(slc)
}
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "slices" |
| 6 | ) |
| 7 | |
| 8 | func main() { |
| 9 | slc := []string{"a","b","c","d","e","f","g","h"} |
| 10 | itemsToPush := []string{"d","g"} |
| 11 | fmt.Println(slc) |
| 12 | for i, s := range slc { |
| 13 | // Move "d" and "g" to the start of slc |
| 14 | // The order of moved items will be reversed |
| 15 | if slices.Contains(itemsToPush, s) { |
| 16 | tmp := []string{s} |
| 17 | for ii:=i; ii > 0; ii-- { |
| 18 | slc[ii] = slc[ii-1] |
| 19 | } |
| 20 | slc = append(tmp, slc[1:]...) |
| 21 | } |
| 22 | } |
| 23 | fmt.Println(slc) |
| 24 | } |
| 25 |