Recursion is a process in which a function calls itself implicitly or explicitly and the corresponding function is called recursive function. Go language supports special feature called anonymous function. It is a function that doesn’t contain any name. It is used to create an inline function. Recursive functions can be declared & defined as anonymous also. A recursive anonymous function is also known as recursive function literal.
Syntax:
func(parameter-list)(return-type){
// code..
// call same function
// within the function
// for recursion
// Use return statement only
// if return-type are given.
return
}()
Example:
package main
import "fmt"
func main() {
var recursiveAnonymous func ()
recursiveAnonymous = func () {
fmt.Println( "Anonymous functions could be recursive." )
recursiveAnonymous()
}
recursiveAnonymous()
}
|
Output:
Anonymous functions could be recursive.
Anonymous functions could be recursive.
Anonymous functions could be recursive.
Anonymous functions could be recursive.
.
.
.
.
Infinite times function calls.
Example 2:
package main
import (
"fmt"
)
func main() {
var recursiveAnonymous func (int)
recursiveAnonymous = func (variable int) {
if variable == - 1 {
fmt.Println( "Welcome to Geeks for Geeks!" )
return
} else {
fmt.Println(variable)
recursiveAnonymous(variable - 1 )
}
}
recursiveAnonymous( 10 )
}
|
Output:
10
9
8
7
6
5
4
3
2
1
0
Welcome to Geeks for Geeks!