-2
type slice []T

func (s *slice) remove(element T) []T {

    newSlice := []T{}

    for _, i:= range s {
        if i != element {
            newSlice = append(newSlice, i)
        }
    }
    return newSlice
}

I am trying to create a generic receiver func to remove elements from a slice, above the code I am working with, but I am getting Undeclared Name: T error..

1
  • You can also check this go/exp library to manipulate generic slices. Commented Sep 28, 2022 at 8:40

1 Answer 1

2

That's because you haven't defined type slice as a generic type. You have just defined it as a slice of type T where type T doesn't exist.

If you do define slice as a generic type, then your approach works:

type slice[T comparable] []T

func (s *slice[T]) remove(element T) []T {

    newSlice := []T{}

    for _, i := range *s {
        if i != element {
            newSlice = append(newSlice, i)
        }
    }
    return newSlice
}

(Also needed to change range s to range *s)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.