Lv.的博客

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

 

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

 

 

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

 

 

 

f1 done
f2 done 100
f1 done
f2 done xxxx
f3 done [[hello world 1 3.14]]
posted @ 2017-03-02 14:33  Avatarx  阅读(1835)  评论(0编辑  收藏  举报