package main
import (
"fmt"
)
type Person struct {
name string
age int
}
func main() {
p := []Person {
{"Kate", 20},
{"Simon", 30},
{"John", 28},
{"Lake", 19},
}
n := []string {
"Simon",
"Kate",
"Lake",
}
for idx := 0; idx < len(p); idx++ {
for _, elem := range n {
if p[idx].name == elem {
p = append(p[:idx], p[idx+1:])
idx--
break
}
}
}
fmt.Println(p)
}
我有上面的代码来删除 p 切片中显示在 n 切片中的人。
但是我在编译时遇到以下错误:
./main.go:29:19: cannot use p[idx + 1:] (type []Person) as type Person in append
您的p[idx + 1:]
是[]Person
,如错误所述。
要将多个元素附加到切片,您需要使用展开运算符,如 SliceTricks 页面上给出的示例所示:
p = append(p[:idx], p[idx+1:]...)