40. Go - Callbacks

Callbacks are passing a func as an argument in a func.

package main

import "fmt"

func sumTotal(l []int) int {
    total := 0

    for _, e := range l {
        total += e
    }

    return total
}

func oddOnly(f func(l []int) int, l []int) int {
    oddList := []int{}

    for _, e := range l {
        if (e % 2) != 0 {
            oddList = append(oddList, e)
        }
    }

    return f(oddList)
}

func main() {
    numList := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    fmt.Println(oddOnly(sumTotal, numList))
}



Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort