On Sun, Oct 1, 2023 at 7:30 PM Jon Watte <jwa...@gmail.com> wrote: > I want to implement a generic function to "remove nil values from a > slice." This should be able to remove nil instances of error, for example. > So, let's say I have: > > var arg = []error{nil, errors.New("oh noes"), nil} > > Unfortunately, this doesn't work: > > func Compact[T comparable](s []T) T { > ... > if s[i] == nil { > > because "error" is not comparable. >
Actually, error is comparable. See https://go.dev/play/p/ymBOc5JQyJT The problem with your code is that "T comparable" guarantees that two values of type T can be compared, but does not guarantee you can compare a value of type T to nil. For example, int is a comparable type, but you can't compare an int to nil. See https://go.dev/play/p/SETrraZ7vkR, which produces the error message: ./prog.go:11:11: invalid operation: t != nil (mismatched types T and untyped nil) This also doesn't work: > > func Compact[T any](s []T) T { > var zero T > ... > if s[i] == zero { > > because T is not a comparable constraint. > You can fix this by making T comparable instead of any. But then the function will also remove 0 from int slices, "" from string slices, etc. https://go.dev/play/p/NigMasu1aL1 -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAADvV_stLn9%3DCXnydGWQgmP1CEFq_10bj96FpezTb6%3DqVBFSbQ%40mail.gmail.com.