DEV Community

Cover image for First class functions in Go
Srinivas Kandukuri
Srinivas Kandukuri

Posted on

First class functions in Go

1. Higher Order functions

In Go,language, a function is called a Higher order function it should full fills one of the below conditions.

1. Passing function as an argument to other function.

func(f) f
Enter fullscreen mode Exit fullscreen mode

Note : passing function as an argument is also known as a callback function or first-class function

2. Returning Functions From Another Functions

func fun(f) f{
 return func(){
     //body
  }
}
Enter fullscreen mode Exit fullscreen mode

Ex:1

func sum(add func(a,b, int) int){
    fmt.println(add(30,20))
}
func main(){
    f := func(a, b int) int {
        return a+b
    }
    sum(f)
}
Enter fullscreen mode Exit fullscreen mode

Ex:2

In this example we defined simple as return function

func simple() func(a,b int) int{
    f := func(a,b int) int{
        return a+b
    }
    return f
}

func main(){
    s:= simple()
    fmt.println(s(20,30))
}
Enter fullscreen mode Exit fullscreen mode

2. Anonymous functions

A function without any name is called antonymous function

Ex:1

first := func(){
    fmt.Println("inside the anonymous function")
}
first()
fmt.println("%T", first)
Enter fullscreen mode Exit fullscreen mode

Ex:2

func(str string){
    fmt.println("inside the anonymous function", str)
}("sk")
Enter fullscreen mode Exit fullscreen mode

3. User defined function type

in the below example add is the user defined type as function

type add func(a, b int) int

func main(){
    var a add = func(a , b int) int{
        return a+b
    }
    s :=a(50,5)
    fmt.println("sum", s)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
c4r4x35 profile image
Srinivas Kandukuri

More useful links in GO
dev.to/c4r4x35/golang-useful-links...