Home > Backend Development > Golang > golang function method passed as parameter

golang function method passed as parameter

WBOY
Release: 2024-04-22 17:39:01
Original
399 people have browsed it

Go function methods are passed as parameters: Go functions can be passed as parameters of other functions. Code can be organized into modular and reusable pieces. Practical case: You can use the print function as a parameter to print slice elements.

golang function method passed as parameter

Passing function methods as parameters in Go language

Function in Go is a first-class citizen, so they can be used as Pass parameters to other functions. This allows you to organize your code into modular and reusable pieces.

Syntax

func f(a int, fn func(int)) {
    fn(a)
}
Copy after login

In this example, the f function receives two parameters: an int and a function type of func(int) function.

Practical Case: Printing Slice Elements

Let us write a function to print slice elements that receives the print function as a parameter.

package main

import "fmt"

// PrintSlice 使用给定的打印函数打印切片元素
func PrintSlice(s []int, fn func(int)) {
    for _, v := range s {
        fn(v)
    }
}

func main() {
    numbers := []int{1, 2, 3, 4, 5}

    // 使用 lambda 表达式打印元素
    PrintSlice(numbers, func(n int) { fmt.Println(n) })

    // 使用命名函数打印元素
    PrintSlice(numbers, func(x int) { fmt.Printf("%d ", x) })
}
Copy after login

Output:

1
2
3
4
5
1 2 3 4 5 
Copy after login

In this example, the PrintSlice function accepts a slice and a print function. It then loops through the slice and passes each element to the print function.

The above is the detailed content of golang function method 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