函数可以作为参数传递吗?

编程入门 行业动态 更新时间:2024-10-23 21:38:18
本文介绍了函数可以作为参数传递吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Java中,我可以做类似

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 "" }) }

播放: play.golang/p/XNMtrDUDS0

游览: tour.golang/moretypes/25 (函数闭包)

更多推荐

函数可以作为参数传递吗?

本文发布于:2023-07-31 15:42:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1260025.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!