Append Slice

package main

import (
	"fmt"
)

func main() {
	var s1 = []int{1,2,3}
	var s2 = []int{4,5,6}
	s1 = append(s1, s2...)
	fmt.Println(s1) // [1 2 3 4 5 6]
}

Copy

package main

import (
	"fmt"
)

func main() {
	a := []int{1,2,3,4}
	b := make([]int, len(a))
	copy(b, a)
	
	fmt.Println("b: ", b)

	c := append([]int(nil), a...)
	fmt.Println("c: ", c)
	
	// or
	d := append(a[:0:0], a...)
	fmt.Println("d: ", d)
}

b:  [1 2 3 4]
c:  [1 2 3 4]
d:  [1 2 3 4]

剪切

package main

import (
	"fmt"
)

func main() {
	var a = []int{1,2,3,4}
	a = append(a[:1], a[2:]...)
	fmt.Println(a)
}

[1 3 4]

删除元素

package main

import (
	"fmt"
)

func main() {
	var a = []int{1,2,3,4}
	a = append(a[:0], a[0+1:]...)
	// or
	// a = a[:i+copy(a[i:], a[i+1:])]
	// fmt.Println(a)
	
	fmt.Println(a)
}

[2 3 4]

Expand

package main

import (
	"fmt"
)

func main() {
	var a = []int{1,2,3,4}
	a = append(a[:2], append(make([]int, 3), a[2:]...)...)
	fmt.Println(a) // [1 2 0 0 0 3 4]
}

Extend

package main

import (
	"fmt"
)

func main() {
	var a = []int{1,2,3,4}
	a = append(a, make([]int, 3)...)
	fmt.Println(a) // [1 2 3 4 0 0 0]
}

Push

a = append(a, x)

Pop

package main

import (
	"fmt"
)

func main() {
	var x int
	var a = []int{1,2,3,4}
	x, a = a[len(a)-1], a[:len(a)-1]
	fmt.Println(x, a) // 4 [1 2 3]
}

Push Front

package main

import (
	"fmt"
)

func main() {
	// var x int
	var a = []int{1,2,3,4}
	a = append([]int{10}, a...)
	fmt.Println(a) // [10 1 2 3 4]
}

Pop Front

x, a = a[0], a[1:]

Reverse

package main

import (
	"fmt"
)

func main() {
	
	var a = []int{1,2,3,4}
	for i := len(a)/2-1; i >= 0; i-- {
		opp := len(a)-1-i
		a[i], a[opp] = a[opp], a[i]
	}
	fmt.Println(a) // [4 3 2 1]
}
package main

import (
	"fmt"
)

func main() {
	var a = []int{1,2,3,4}
	for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
		a[left], a[right] = a[right], a[left]
	}
	fmt.Println(a) // [4 3 2 1]
}