golang function slice passed as parameter

WBOY
Release: 2024-04-22 16:48:02
Original
726 people have browsed it

Function slices in Go language can be passed as parameters to enhance code flexibility. The syntax is as follows: func function(fn func([]int) []int, slice []int) []int, where function receives function slice fn and slice slice as parameters.

golang function slice passed as parameter

Passing function slices as parameters in Go language

In Go language, functions can be passed as parameters to other functions. This is a powerful technique that makes your code more flexible and reusable.

Syntax

The syntax for passing function slices as parameters is as follows:

func function(fn func([]int) []int, slice []int) []int
Copy after login

function is the receiving function slice Functions with fn and sliceslice as parameters. func defines the type of function slice, which receives an integer slice of length N and returns an integer slice of length M.

Practical Case

Let’s look at a practical case of passing function slices as parameters. Suppose we have a function apply that takes a function slice and a slice and applies each function in the function slice to each element in the slice.

package main

import "fmt"

func main() {
    // 定义函数切片
    fns := []func(int) int{
        func(i int) int { return i + 1 },
        func(i int) int { return i * 2 },
    }

    // 定义切片
    slice := []int{1, 2, 3}

    // 将函数切片和切片传递给 apply 函数
    result := apply(fns, slice)

    // 打印结果
    fmt.Println(result)
}

// apply 函数接收一个函数切片和一个切片,并对切片中的每个元素应用函数切片中的每个函数
func apply(fns []func(int) int, slice []int) []int {
    result := make([]int, len(slice))
    for i, v := range slice {
        for _, fn := range fns {
            result[i] = fn(v)
        }
    }
    return result
}
Copy after login

Output

[]int{2, 4, 6}
Copy after login

The above is the detailed content of golang function slice passed as parameter. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template