Go Filter Slice Example

1. Introduction

Filtering slices is a common operation in Go programming. It involves iterating over a collection and selecting elements that meet certain criteria. Go doesn't have a built-in filter function, but we can easily implement our own. This blog post will demonstrate how to filter a slice of integers to include only even numbers.


Filtering a slice involves creating a new slice and appending only those elements that satisfy a specified condition. In our example, the condition will be that a number is even.

2. Program Steps

1. Create a slice of integers to be filtered.

2. Write a function filter that takes a slice and a function as parameters. The function defines the condition used for filtering.

3. Inside the filter function, iterate over the input slice, apply the condition, and append elements that meet the condition to a new slice.

4. Call the filter function with the slice and a function that checks for even numbers.

5. Print the filtered slice.

3. Code Program

package main

import "fmt"

// isEven is a predicate function that determines if a number is even.
func isEven(n int) bool {
	return n%2 == 0

// filter iterates over a slice of integers, applying a predicate function to each item.
// It returns a new slice containing all items that satisfy the predicate.
func filter(slice []int, condition func(int) bool) []int {
	var filtered []int
	for _, v := range slice {
		if condition(v) {
			filtered = append(filtered, v) // Append only if the condition is true
	return filtered

func main() {
	// Original slice of integers
	numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

	// Filter the slice to include only even numbers
	evenNumbers := filter(numbers, isEven)

	// Print the result
	fmt.Println("Even numbers:", evenNumbers)


Even numbers: [2 4 6 8 10]


1. package main - Declares the main package, indicating that the package is executable.

2. import "fmt" - Imports the Format package, which is used for formatted I/O.

3. func isEven(n int) bool - Defines a predicate function that checks if a number is even.

4. func filter(slice []int, condition func(int) bool) []int - Defines the filter function. It takes a slice of integers and a function as parameters. The function passed as condition is used to determine if an element should be included in the result.

5. Inside the filter function, a loop iterates over each element in the input slice. If an element satisfies the condition, it's appended to the filtered slice.

6. The main function initializes a slice of integers named numbers.

7. The filter function is then called with numbers and the isEven predicate function, resulting in a slice of even numbers named evenNumbers.

8. The fmt.Println function is used to print the filtered slice of even numbers.

9. The output confirms that the slice has been correctly filtered to include only the even numbers [2 4 6 8 10].