100daysofcode - Day 09
Hello folks, another day, and some new progress in this amazing journey. Today marks our 9th day in the 100days code challenge. And in today’s post, we will continue our tour on some new concepts in Golang. Where we will talk about anonymous functions, nested functions, and closures ![]()
![]()
![]()
What is an anonymous function in Golang ?
- In simple terms an anonymous function is the one declared without any named identifier.
- It behave as any other standard function, where it can accept inputs, compute them and return a result
-
An anonymous function can be assigned to a variable.
-
Example
package main
import "fmt"
func main() {
// anonymous function
var helloCommunity = func() {
fmt.Println("Hello, MongoDB community 🥰 🚀")
}
// calling the function
helloCommunity()
// anonymous function with arguments
var multiplication = func(a, b int) int {
return a * b
}
// passing arguments to the anonymous function
fmt.Println("Multiplication result: ",multiplication(5, 4))
}
What is a nested function ? And does Golang support such functions ?
-
A nested function is a function which is defined within another function, the enclosing function.
-
A nested function is it self invisible outside of its immediately enclosing function, but can see (access) all local objects (data, functions, types, etc.) of its immediately enclosing function.
-
Golang allow us to deal with such functions, on the fly.
-
Example
package main
import (
"fmt"
str "strings"
)
// The outer function
func hello(name string) {
// The inner function using the args name of its enclosing function
var displayName = func() {
updatedName := str.ToUpper(name)
fmt.Println("Hello", updatedName)
}
// call the inner function
displayName()
}
func main() {
// Call the parent outer function
hello("elie")
// Output: Hello ELIE
}
A function that returns a function ??
-
Yeh, in Golang we can simply create a function that returns a function, let us understand how we can do that, in the following example.
-
Example
package main
import "fmt"
func helloWorld() func() {
return func() {
fmt.Println("Hello World")
}
}
func main() {
functionInsideFunction := helloWorld()
functionInsideFunction()
}
What is a closure in Golang ??
-
A function that references variables outside its body or scope, or in other words we can define it as an inner function that has an access to the variables in the scope in which it was created.
-
Example:
package main
import (
"fmt"
"strings"
)
// The outer function that return another anonymous function
func displayNameInLoweCase(name string) func() string {
greeting := "Hello,"
// The anonymous inner function that return
// the name passed from the outer function concatenated with a string in lower case
return func() string {
transformedName := strings.ToLower(name)
return greeting + transformedName
}
}
func main() {
lower := displayNameInLoweCase("JOHN")
fmt.Println(lower())
}