不能使用 p[idx + 1:](类型 []Person) 作为追加中的 Person 类型

  • 本文关键字:类型 Person 追加 idx 不能 go
  • 更新时间 :
  • 英文 :

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:]...)

相关内容

最新更新