0
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)
}

I have the code as above to remove the persons in p slice who displayed in n slice.

But I got the following error when compile:

./main.go:29:19: cannot use p[idx + 1:] (type []Person) as type Person in append
Biffen
  • 6,249
  • 6
  • 28
  • 36
NghiaTran
  • 55
  • 1
  • 4

1 Answers1

7

Your p[idx + 1:] is a []Person, as the error states.

To append multiple elements to a slice, you need to use the spread operator, like in the example given on the SliceTricks page:

p = append(p[:idx], p[idx+1:]...)
xarantolus
  • 1,961
  • 1
  • 11
  • 19