函数可以在Go中作为参数传递吗? [英] Can Functions be passed as parameters in Go?
本文介绍了函数可以在Go中作为参数传递吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中,我可以做一些类似于 derp(new Runnable {public void run(){/ *稍后运行它* /}})
和run代码在稍后的方法中。处理(匿名内部类)是一件痛苦的事情,但它可以完成。
In Java I can do something like derp(new Runnable { public void run () { /* run this sometime later */ } })
and "run" the code in the method later. It's a pain to handle (anonymous inner class), but it can be done.
Go有一些可以促进函数/回调作为参数传入的东西吗?
Does Go have something that can facilitate a function/callback being passed in as a parameter?
推荐答案
是的,考虑一下这些例子:
Yes, consider some of these examples:
package main
import "fmt"
// convert types take an int and return a string value.
type convert func(int) string
// value implements convert, returning x as string.
func value(x int) string {
return fmt.Sprintf("%v", x)
}
// quote123 passes 123 to convert func and returns quoted string.
func quote123(fn convert) string {
return fmt.Sprintf("%q", fn(123))
}
func main() {
var result string
result = value(123)
fmt.Println(result)
// Output: 123
result = quote123(value)
fmt.Println(result)
// Output: "123"
result = quote123(func(x int) string { return fmt.Sprintf("%b", x) })
fmt.Println(result)
// Output: "1111011"
foo := func(x int) string { return "foo" }
result = quote123(foo)
fmt.Println(result)
// Output: "foo"
_ = convert(foo) // confirm foo satisfies convert at runtime
// fails due to argument type
// _ = convert(func(x float64) string { return "" })
}
播放: http:/ /play.golang.org/p/XNMtrDUDS0
旅程: https://tour.golang.org/moretypes/25 (功能闭包)
这篇关于函数可以在Go中作为参数传递吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文