How to apply a callback to an array (apply a function to each element) in Go

2 Answers

0 votes
package main

import "fmt"

// Map applies a callback function to each element of a slice.
// The callback receives the element value and returns a new value.

// The Map function
// Takes a slice of integers
// Takes a callback function
// Applies the callback to each element
// Returns a new slice
func Map(nums []int, callback func(int) int) []int {
    // Create a new slice to store results
    result := make([]int, len(nums))

    // Loop through the slice and apply the callback
    for i, v := range nums {
        result[i] = callback(v)
    }

    return result
}

// Example callback: double the number
// The callback type
// Go uses func(int) int as a function type.
// You can pass any function matching that signature.

func Double(x int) int {
    return x * 2
}

func main() {
    numbers := []int{5, 10, 15, 20}

    // Apply the callback to each element
    doubled := Map(numbers, Double)

    // Print results
    fmt.Println(doubled) 
}



/*
run:

[10 20 30 40]

*/

 



answered Mar 20 by avibootz
0 votes
package main

import "fmt"

// Modifies the slice in place
func ForEach(nums []int, callback func(int) int) {
    for i, v := range nums {
        nums[i] = callback(v)
    }
}

// Example callback: double the number
// The callback type
// Go uses func(int) int as a function type.
// You can pass any function matching that signature.

func Double(x int) int {
    return x * 2
}

func main() {
    numbers := []int{5, 10, 15, 20}

    // Apply the callback to each element
    ForEach(numbers, Double)

    // Print results
    fmt.Println(numbers) 
}



/*
run:

[10 20 30 40]

*/

 



answered Mar 20 by avibootz
...