Sling Academy
Home/Golang/How to filter strings in a slice in Go

How to filter strings in a slice in Go

Last updated: November 21, 2024

Filtering strings within a slice in Go can be accomplished by iterating over each element and selecting the ones that meet certain criteria. This article will guide you through basic, intermediate, and advanced approaches to accomplish this task.

Basic Filtering

In the most basic form, you can filter strings in a slice by using a loop and simple conditional logic within that loop.


package main

import (
    "fmt"
)

func main() {
    strings := []string{"apple", "banana", "avocado", "cherry"}
    filter := "a"
    result := []string{}

    for _, str := range strings {
        if contains(str, filter) {
            result = append(result, str)
        }
    }

    fmt.Println("Filtered strings:", result)
}

func contains(s, substr string) bool {
    return len(s) >= len(substr) && s[:len(substr)] == substr
}

This code filters the slice to include only strings that begin with the letter 'a'.

Intermediate Filtering with Built-in Functions

You can enhance the utility of your filter by using Go's strings package.


package main

import (
    "fmt"
    "strings"
)

func main() {
    stringsSlice := []string{"apple", "banana", "avocado", "cherry"}
    filter := "a"
    result := []string{}

    for _, str := range stringsSlice {
        if strings.HasPrefix(str, filter) {
            result = append(result, str)
        }
    }

    fmt.Println("Filtered strings:", result)
}

Here, the strings.HasPrefix function is used to filter strings starting with the letter 'a'.

Advanced Filtering with Higher-Order Functions

For more complex filter criteria, using higher-order functions can make your code cleaner and more reusable.


package main

import (
    "fmt"
)

func filterStrings(strings []string, test func(string) bool) []string {
    result := []string{}
    for _, str := range strings {
        if test(str) {
            result = append(result, str)
        }
    }
    return result
}

func main() {
    stringsSlice := []string{"apple", "banana", "avocado", "cherry", "apricot"}

    result := filterStrings(stringsSlice, func(s string) bool {
        return len(s) >= 6 // Filter strings with length >= 6
    })

    fmt.Println("Filtered strings:", result)
}

In this example, a higher-order filter function was used to select strings based on their length. You can adapt this function to apply any filtering logic you need.

These examples demonstrate progressively more complex and reusable approaches to filtering strings within a slice in Go. Start with the basic example and experiment with incorporating more advanced features as you become comfortable.

Next Article: Filtering composite types in a slice in Go

Previous Article: Filtering numbers in a slice in Go

Series: Working with Slices in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant