Home > Backend Development > Golang > Can Go Functions Be Passed as Parameters?

Can Go Functions Be Passed as Parameters?

Susan Sarandon
Release: 2024-12-03 19:55:10
Original
593 people have browsed it

Can Go Functions Be Passed as Parameters?

Can Functions Be Passed as Parameters in Go?

Java allows passing functions as parameters through the use of anonymous inner classes. Does Go provide a similar mechanism to facilitate this functionality?

Answer:

Absolutely! Go supports passing functions as parameters through anonymous functions and closures. Here are a few examples:

Example 1:

package main

import "fmt"

type convert func(int) string

func value(x int) string {
    return fmt.Sprintf("%v", x)
}

func quote123(fn convert) string {
    return fmt.Sprintf("%q", fn(123))
}

func main() {
    result := quote123(value)
    fmt.Println(result) // Output: "123"
}
Copy after login

In this example, the convert function type is defined to take an integer and return a string. The value function implements convert by returning the string representation of the input integer. The quote123 function accepts a convert function as an argument and returns a quoted string representation of the result of calling the function with the value 123.

Example 2:

package main

import "fmt"

func main() {
    result := quote123(func(x int) string { return fmt.Sprintf("%b", x) })
    fmt.Println(result) // Output: "1111011"
}
Copy after login

Here, an anonymous function is passed as an argument to the quote123 function. The anonymous function converts the input integer into its binary string representation.

Example 3:

package main

import "fmt"

func main() {
    foo := func(x int) string { return "foo" }
    result := quote123(foo)
    fmt.Println(result) // Output: "foo"
}
Copy after login

In this case, a named function, foo, is passed as an argument to quote123. The foo function simply returns the string "foo" for any input.

These examples demonstrate the flexibility and power of passing functions as parameters in Go, enabling you to create generic and reusable code.

The above is the detailed content of Can Go Functions Be Passed as Parameters?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template