In Go, you can filter elements from a slice based on a condition by using a combination of the filter
function and a callback function.
Here is an example of how you can filter elements from a slice based on a specific condition:
func checkCondition(element string) bool {
// return true if the condition is met, false otherwise
// for example, let's filter elements that start with the letter "a"
return strings.HasPrefix(element, "a")
}
filter
function that takes in the slice and the callback function, and returns a new slice with only the filtered elements:func filter(s []string, callback func(string) bool) []string {
var filteredSlice []string
for _, element := range s {
if callback(element) {
filteredSlice = append(filteredSlice, element)
}
}
return filteredSlice
}
filter
function by passing the slice and the callback function, and store the returned filtered slice:func main() {
originalSlice := []string{"apple", "banana", "avocado", "plum", "orange"}
filteredSlice := filter(originalSlice, checkCondition)
fmt.Println(filteredSlice)
// Output: [apple avocado]
}
In this example, the filter
function iterates over each element in the originalSlice and calls the checkCondition
callback function for each element. If the condition is true, the element is appended to the filteredSlice. Finally, the filteredSlice is returned and printed.