Takes two input integer and returns an integer (common int type input if both are the same type else individually)
package main
import (
"fmt"
)
func plus(a ,b int) int{
return a + b
}
func main() {
r := plus(3,4)
fmt.Println(r)
}
Multiple return from function
package main
import (
"fmt"
)
func plus(a ,b int) (int,int){
c := a + b
d := a*b
return c,d
}
func main() {
r,r1 := plus(3,4)
fmt.Println(r,r1)
}
Question: you can also pass list
Answer:
Multiple Arguments passing and receiving
package main
import (
"fmt"
)
// receiving multiple elements as arguments in func
func sum(num ...int){
i:=0
total := 0
for i=0; i< len(num); i++ {
total = total + num[i]
}
fmt.Println(total)
}
func main() {
// variable length is denoted by ... in go
sum(1,2)
sum(1,2, 23,53,4)
// passing multiple elements in collections
nums := []int{1,2,3,4}
sum(nums...)
}
Functions examples
Closures
anonymous functions
closures
package main
import (
"fmt"
)
func do_something(i int) func() int{
return func() int{
i = i+1
return i
}
}
func main() {
// annonymous function
variable := do_something(3)
fmt.Println(variable())
}
Recursion
package main
import (
"fmt"
)
// passess something as an argument to function do_something
func do_something(i int) int{
// returns an anonymous function with return type
if i == 0 {
return 1
}
x := i*do_something(i-1)
return x
}
func main() {
// annonymous function
fmt.Println(do_something(3))
}