Pass as an Argument

时尚2025-05-24阅读  37+

Pass as an Argument

Anonymous functions can be passed as arguments to other functions, especially in higher-order functions where this pattern is common.

Example:

go

package main

import "fmt"

// Higher-order function that takes a function as an argument

func applyOperation(a, b int, operation func(int, int) int) int {

return operation(a, b)

}

func main() {

// Define an anonymous function and pass it to applyOperation

result := applyOperation(3, 4, func(x, y int) int {

return x * y

})

fmt.Println(result) // Output: 12

}

3. Assign to a Variable

You can assign an anonymous function to a variable, allowing you to call it whenever needed.

Example:

go

package main

import "fmt"

func main() {

// Assign an anonymous function to a variable

greet := func(name string) {

fmt.Printf("Hello, %s!\n", name)

}

// Call the anonymous function

greet("Alice") // Output: Hello, Alice!

greet("Bob") // Output: Hello, Bob!

}

本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。文内含有的对外跳转链接(包括不限于超链接、二维码、口令等形式),用于传递更多信息,结果仅供参考,今日霍州所有文章均包含本声明。

猜你喜欢