map an array in go

To map an array in Go, you can use a for loop and apply a function to each element of the array. The general syntax to define the function and loop structure is as follows:

main.go
func mapArray(arr []int, f func(int) int) []int {
    result := make([]int, len(arr))
    for i, v := range arr {
        result[i] = f(v)
    }
    return result
}
165 chars
8 lines

Here, arr is the input array of type []int, and f is a function that takes an integer input and returns an integer output. The mapArray function returns a new array of type []int that contains the resulting values after applying the function to each element of the input array.

To use this function, you can define the input array and a function to be applied to each element, like so:

main.go
func main() {
    arr := []int{1, 2, 3, 4, 5}
    f := func(x int) int { return x * 2 }

    mappedArr := mapArray(arr, f)
    fmt.Println(mappedArr) // Output: [2 4 6 8 10]
}
176 chars
8 lines

In this example, the f function multiplies each element of the input array by 2, and the resulting mappedArr is [2 4 6 8 10].

related categories

gistlibby LogSnag