分享
go语言函数作为参数传递
rojas · · 17424 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
go语言函数作为参数传递,目前给我的感觉几乎和C/C++一致。非常的灵活。
import "fmt" import "time" func goFunc1(f func()) { go f() } func goFunc2(f func(interface{}), i interface{}) { go f(i) } func goFunc(f interface{}, args... interface{}) { if len(args) > 1 { go f.(func(...interface{}))(args) } else if len(args) == 1 { go f.(func(interface{}))(args[0]) } else { go f.(func())() } } func f1() { fmt.Println("f1 done") } func f2(i interface{}) { fmt.Println("f2 done", i) } func f3(args... interface{}) { fmt.Println("f3 done", args) } func main() { goFunc1(f1) goFunc2(f2, 100) goFunc(f1) goFunc(f2, "xxxx") goFunc(f3, "hello", "world", 1, 3.14) time.Sleep(5 * time.Second) }
f1 done
f2 done 100
f1 done
f2 done xxxx
f3 done [[hello world 1 3.14]]
转自 http://blog.csdn.net/eclipser1987/article/details/11772539
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信17424 次点击 ∙ 1 赞
上一篇:signals _ golang
下一篇:goinstall
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
go语言函数作为参数传递,目前给我的感觉几乎和C/C++一致。非常的灵活。
import "fmt" import "time" func goFunc1(f func()) { go f() } func goFunc2(f func(interface{}), i interface{}) { go f(i) } func goFunc(f interface{}, args... interface{}) { if len(args) > 1 { go f.(func(...interface{}))(args) } else if len(args) == 1 { go f.(func(interface{}))(args[0]) } else { go f.(func())() } } func f1() { fmt.Println("f1 done") } func f2(i interface{}) { fmt.Println("f2 done", i) } func f3(args... interface{}) { fmt.Println("f3 done", args) } func main() { goFunc1(f1) goFunc2(f2, 100) goFunc(f1) goFunc(f2, "xxxx") goFunc(f3, "hello", "world", 1, 3.14) time.Sleep(5 * time.Second) }
f1 done
f2 done 100
f1 done
f2 done xxxx
f3 done [[hello world 1 3.14]]
转自 http://blog.csdn.net/eclipser1987/article/details/11772539