First class functions in Go

c4r4x35

Srinivas Kandukuri

Posted on December 3, 2022

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
💖 💪 🙅 🚩
c4r4x35
Srinivas Kandukuri

Posted on December 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

First class functions in Go
go First class functions in Go

December 3, 2022