Pass as an Argument

2025-05-24ASPCMS社区 - fjmyhfvclm

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!

}

全部评论