package main import "fmt" func main() { data := []string{"red", "black", "orange", "white", "red", "blue", "blue"} fmt.Println("old data = ", data) afterData := sliceUnique(data) fmt.Println("new data = ", afterData) } func sliceUnique(data []string) []string { out := data[:1] for _, word := range data { i := 0 for ; i < len(out); i++ { if word == out[i] { break } } if i == len(out) { out = append(out, word) } } return out }
打印:
old data = [red black orange white red blue blue]
new data = [red black orange white blue]