Trying to understand generics

package main

import "fmt"

type Container[T any] struct {
	Data []T
}

func (c Container[T]) Filter(f func(T) bool) Container[T] {
	var r Container[T]

	for _, i := range c.Data {
		if f(i) {
			r.Data = append(r.Data, i)
		}
	}

	return r
}

func main() {
	intContainer := Container[int]{
		Data: []int{1, 2, 3, 4, 5},
	}

	fmt.Println(intContainer.Filter(func(v int) bool { return v < 4 }))
}

I would have expected the above to work, but I’m getting the error:

./main.go:13:8: cannot use i (variable of type int) as type T in argument to f
./main.go:14:28: cannot use i (variable of type int) as type T in argument to append

And I don’t understand why. Since I’m initializing the container with T as int, I would expect that the receiver function also to expect T to be an int? So why doesn’t this work?

[edit]
Nevermind… I forgot that I as looping over the slice im getting a index, value. So i was working with the int (key) instead of the value T. The reason I missed it was that even when I solve it Goland keeps complaining about the code. But the example above works now.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.