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

golang function function passed as parameter

PHPz
Release: 2024-04-22 22:12:01
Original
862 people have browsed it

In Go, functions can be passed as parameters to enhance code reusability and maintainability. Syntax: Pass the value of function type, that is, func (parameter list) return value type. Practical case: The function Exclaim takes a string as a parameter, prints the string and adds an exclamation mark. The function PrintWithExcitement receives a function parameter f and uses it to print the string parameter s.

golang function function passed as parameter

Passing functions as parameters in Go

In Go, you can pass a function as a parameter to another function. This allows the creation of reusable and modular code, thereby enhancing code readability and maintainability.

Syntax

To pass a function as a parameter, simply pass it as a value of the function type. The syntax for function types is as follows:

func(参数列表) 返回值类型
Copy after login

For example, consider the following function, which receives a function as a parameter and uses it to print a message:

func PrintMessage(f func(string)) {
    f("Hello, world!")
}
Copy after login

Practical case

Here is a Practical case showing how to create a function and pass it as a parameter to another function:

package main

import "fmt"

// 定义一个函数并将其作为参数传递
func Exclaim(s string) {
    fmt.Println(s + "!")
}

// 定义一个函数,它接收一个函数作为参数
func PrintWithExcitement(s string, f func(string)) {
    f(s)
}

func main() {
    // 传递 Exclaim 函数作为参数
    PrintWithExcitement("Hello", Exclaim)
}
Copy after login

Running the above code will output:

Hello!
Copy after login

This code shows how to define a functionExclaim and pass it as a parameter to function PrintWithExcitement. Then, PrintWithExcitement calls the Exclaim function to print the message "Hello!" followed by an exclamation mark.

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