filter list in go

To filter a list in Go, you can use either functional programming techniques or traditional iteration. Here are examples for both methods:

Using Functional Programming:

main.go
package main

import (
    "fmt"
)

func isEven(n int) bool {
    return n%2 == 0
}

func filter(numbers []int, callback func(int) bool) []int {
    filtered := []int{}
    for _, n := range numbers {
        if callback(n) {
            filtered = append(filtered, n)
        }
    }
    return filtered
}

func main() {
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    fmt.Println(filter(numbers, isEven))
    // Output: [2 4 6 8 10]
}
445 chars
26 lines

In this example, we defined a function isEven which returns true if the provided integer is even. Then, we defined a filter function which takes a list of integers and a callback function and returns a new list with only those integers for which the callback function returns true. Finally, in the main function, we applied the filter function to our numbers list and the isEven function as the callback to get a new list containing only even numbers.

Using Traditional Iteration:

main.go
package main

import (
    "fmt"
)

func main() {
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    filtered := []int{}
    for _, n := range numbers {
        if n%2 == 0 {
            filtered = append(filtered, n)
        }
    }
    fmt.Println(filtered)
    // Output: [2 4 6 8 10]
}
295 chars
18 lines

In this example, we simply loop through our numbers list using a for loop and add each even number to a new list called filtered. Finally, we print out the filtered list.

gistlibby LogSnag