go语言将函数作为参数传递

Go语言函数作为参数传递,目前给我的感觉几乎和C/C++一致。非常的灵活。

[plain]view plaincopy

  1. import "fmt"
  2. import "time"
  3. func goFunc1(f func()) {
  4. go f()
  5. }
  6. func goFunc2(f func(interface{}), i interface{}) {
  7. go f(i)
  8. }
  9. func goFunc(f interface{}, args... interface{}) {
  10. if len(args) > 1 {
  11. go f.(func(...interface{}))(args)
  12. } else if len(args) == 1 {
  13. go f.(func(interface{}))(args[0])
  14. } else {
  15. go f.(func())()
  16. }
  17. }
  18. func f1() {
  19. fmt.Println("f1 done")
  20. }
  21. func f2(i interface{}) {
  22. fmt.Println("f2 done", i)
  23. }
  24. func f3(args... interface{}) {
  25. fmt.Println("f3 done", args)
  26. }
  27. func main() {
  28. goFunc1(f1)
  29. goFunc2(f2, 100)
  30. goFunc(f1)
  31. goFunc(f2, "xxxx")
  32. goFunc(f3, "hello", "world", 1, 3.14)
  33. time.Sleep(5 * time.Second)
  34. }
f1 done

f2 done 100

f1 done

f2 done xxxx

f3 done [[hello world 1 3.14]]