怎樣刪除取出切片中的不重複元素,還不會造成記憶體逃逸

haoc7發表於2017-09-22
package main

import (
    "fmt"
)

func uniqueSlice(slice *[]string) {
    found := make(map[string]int)
    total := 0
    for i, val := range *slice {
        if _, ok := found[val]; !ok {
            (*slice)[total] = (*slice)[i]
            found[val]++
            total++
        }
    }

    (*slice) = (*slice)[:total]
}
func main() {
    s := []string{"1", "1", "3", "2", "4", "2", "3", "1", "4"}
    uniqueSlice(&s)
    fmt.Println(s)
}
MacBook-Pro:slice haoc$ go build -gcflags '-m' ./rm_duplicate.go
# command-line-arguments
./rm_duplicate.go:18:11: uniqueSlice ignoring self-assignment to *slice
./rm_duplicate.go:7:27: leaking param content: slice
./rm_duplicate.go:8:15: uniqueSlice make(map[string]int) does not escape
./rm_duplicate.go:22:15: []string literal escapes to heap
./rm_duplicate.go:24:13: s escapes to heap
./rm_duplicate.go:23:14: main &s does not escape
./rm_duplicate.go:24:13: main ... argument does not escape
更多原創文章乾貨分享,請關注公眾號
  • 怎樣刪除取出切片中的不重複元素,還不會造成記憶體逃逸
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章