package main
import "fmt"
func scliceTest(a []int) {
a[1] = 5
a = append(a, 10)
}
func main() {
// 创建
a := []int{1, 2, 3, 4, 5}
fmt.Println(a)
b := make([]int, 5)
b = append(b, 2)
fmt.Println(b) //[0 0 0 0 0 2]
// 迭代切片
for i, v := range b {
fmt.Printf("b[%d] = %d\n", i, v)
}
scliceTest(b)
fmt.Println(b) // [0 0 0 0 0 2] // 传递slice,复制slice 指向同一块底层数组,所以能修改b的值
}
slice的零值是nil
,一个 nil 的 slice 的长度和容量是 0。
func main() {
var z []int
fmt.Println(z, len(z), cap(z)) // [] 0 0
if z == nil {
fmt.Println("nil!")
}
}
slice模拟一个stack
stack := []int{}
stack = append(stack, 1)
stack = append(stack, 2)
stack = append(stack, 3) // push v
fmt.Println(stack) // [1 2 3]
top := stack[len(stack)-1]
fmt.Println(top) // 3
stack = stack[:len(stack)-1] // pop
fmt.Println(stack) // [1 2]
去除slice中的空字符串
// Nonempty is an example of an in-place slice algorithm.
package main
import "fmt"
// nonempty returns a slice holding only the non-empty strings.
// The underlying array is modified during the call.
func nonempty(strings []string) []string {
i := 0
for _, s := range strings {
if s != "" {
strings[i] = s
i++
}
}
return strings[:i]
}
删除slice中某个元素
func remove(slice []int, i int) []int {
copy(slice[i:], slice[i+1:])
return slice[:len(slice)-1]
}
func main() {
s := []int{5, 6, 7, 8, 9}
fmt.Println(remove(s, 2)) // "[5 6 8 9]"
}
slice去重
package main
import "fmt"
func rmRepeatStr(arr [] int) []int {
tmpmap := make(map[int]byte)
i := 0
for _, v := range arr {
tmpmap[v]++
if tmpmap[v] == 1 {
arr[i] = v
i++
}
}
return arr[:i]
}
func main() {
arr := []int{1, 3, 4, 1, 2, 2, 5}
ret := rmRepeatStr(arr)
fmt.Println(ret)
}