In this post, we explore ways to replicate Python's list comprehension in Go, specifically the syntax:
array = [a for a in anotherArray if (some condition)]
Go offers a filter library proposed by Rob Pike. This library provides a Choose() function that takes a slice and a boolean function as arguments. It returns a new slice containing only elements that meet the specified condition.
For example:
import "google.golang.org/x/exp/slices" func TestChoose(t *testing.T) { a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} expect := []int{2, 4, 6, 8} result := slices.Choose(a, isEven) }
While the filter library offers a convenient solution, its official documentation advises against its use, due to its decreased efficiency compared to explicit for loops.
The Go documentation recommends using for loops as an alternative to list comprehensions. They offer a more efficient solution, especially in situations where one needs to control the order of operations or limit data generation.
For example, the following code calculates the minimum value in a nested loop:
min := min(abs(a[i], b[j]) for i in range(n) for j in range(i, n))
The above is the detailed content of How to Achieve Python's List Comprehension Functionality in Go?. For more information, please follow other related articles on the PHP Chinese website!