Need help understanding some Go code

I’m new to Go and to practice I do some coding exercice on Exercism. I stubbled on a particular exercice in which I’m having a hard time undestanding the solution. Here’s the code:

   // Ints defines a collection of int values
   type Ints []int

// Lists defines a collection of arrays of ints
type Lists [][]int

// Strings defines a collection of strings
type Strings []string

// Keep filters a collection of ints to only contain the members where the provided function returns true.
func (i Ints) Keep(strainer func(int) bool) (o Ints) {
	for _, v := range i {
		if strainer(v) {
			o = append(o, v)
		}
	}

	return
}

// Discard filters a collection to only contain the members where the provided function returns false.
func (i Ints) Discard(strainer func(int) bool) Ints {
	return i.Keep(func(n int) bool { return !strainer(n) })
}

My issue here is the Discard method we are returning a Ints type value that calls the Keep method, but I don’t understand the return statement afterward (inside the curly braces), given that the function Keep is supposed to return a value of type Ints, why is there a boolean statement inside the function. If someone could break down the Discard function for me, I would be thankful.
Thanks

Discard calls Keep with a negated predicate.

That’s the trick.

“Discard all even values” does mean “keep all odd values”, the implementation of Discard uses exactly this.

Hi Rachid,

The Discard method can be written like this:

func (i Ints) Discard(strainer func(int) bool) Ints {
   myStrainer:= func(n int) bool { return !strainer(n)}
   return i.Keep(myStrainer)
}

I hope it is clear why this method compiles: it returns what is returned by the call to i.Keep() which is Ints. The bool is returned by the function passed to i.Keep().

Thanks I got it now, the thing is when I read the code I didn’t notice that it was an anonymous function and it confused me as a result.

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