slice
Contains
- before
func ContainsBefore(numbers []int, n int) bool { for _, number := range numbers { if number == n { return true } } return false }
- after
import "slices" ... slices.Contains(numbers, 3)
Equal
- before
func EqualBefore(a, b []int) bool { if len(a) != len(b) { return false } for i, number := range a { if number != b[i] { return false } } return true }
- after
import "slices" ... slices.Equal(a, b)
Compact
- before
func CompactBefore(numbers []int) []int { var result []int for _, number := range numbers { if len(result) == 0 || result[len(result)-1] != number { result = append(result, number) } } return result }
- after
import "slices" ... compacted := slices.Compact(numbers) // for numbers []int{1, 2, 3, 3, 4, 5, 5} // compacted is []int{1, 2, 3, 4, 5}
Reverse
- before
func ReverseBefore(numbers []int) { for i := 0; i < len(numbers)/2; i++ { j := len(numbers) - i - 1 numbers[i], numbers[j] = numbers[j], numbers[i] } }
- after
import "slices" ... slices.Reverse(numbers)
新的 slices 包还含有很多有用的函数,比如 Min,Max 等等,详情可以查看这里。
map
Equal
- before
func BeforeEqual(m1, m2 map[string]string) bool { if len(m1) != len(m2) { return false } for k, v := range m1 { if v != m2[k] { return false } } return true }
- after
import "maps" ... maps.Equal(m1, m2)
Delete
- before
func DeleteBefore(m map[string]string) { for k, v := range m { if v == "before" { delete(m, k) } } }
- after
import "maps" ... maps.DeleteFunc(m, func(k, v string) bool { return v == "after" })
Clear
函数Clear
删除映射中的所有元素或将切片中的所有元素归零。
- slice
numbers := []int{1, 2, 3, 4, 5} clear(numbers) // After clear // Capacity is 5 // Lenght is 5 // numbers is [0 0 0 0 0]
- map
m := map[string]string{ "first": "before", "second": "after", } clear(m) // After clear // Lenght is 0 // map is empty
附录:
slices 包文档:https://pkg.go.dev/slices