First class functions in Go

前端 未结 5 1544
鱼传尺愫
鱼传尺愫 2021-01-30 08:49

I come from JavaScript which has first class function support. For example you can:

  • pass a function as a parameter to another function
  • return a function f
5条回答
  •  攒了一身酷
    2021-01-30 09:19

    While you can use a var or declare a type, you don't need to. You can do this quite simply:

    package main
    
    import "fmt"
    
    var count int
    
    func increment(i int) int {
        return i + 1
    }
    
    func decrement(i int) int {
        return i - 1
    }
    
    func execute(f func(int) int) int {
        return f(count)
    }
    
    func main() {
        count = 2
        count = execute(increment)
        fmt.Println(count)
        count = execute(decrement)
        fmt.Println(count)
    }
    
    //The output is:
    3
    2
    

提交回复
热议问题