In Go, functions are the basic building blocks. A function is used to break a large problem into smaller tasks. We can invoke a function several times, hence functions promote code reusability. There are 3 types of functions in Go:
- Normal functions with an identifier
- Anonymous or lambda functions
- Method (A function with a receiver)
Function parameters, return values, together with types, is called function signature.
Function cannot be declared inside another function. If we want to achieve this, we can do this by anonymous function.
Go Function Example
Package main
import “fmt”
type Employee struct {
fname string
lname string
}
func ( emp Employee ) full name (){
fmt.Println(emp.fname +” “+ emp.lname)
}
func main() {
e1 := Employee {” John”,”Pointing”}
e1.fullname()
}
Output:
John Ponting
Go Function with Return
Let’s see an example of function with return value.
package main
import (
“fmt”
)
func fun() int {
return 123456789
}
func main() {
x := fun()
fmt.Println(x)
}
Output:
123
Go Function with Multiple Return
Let’s see an example of a function which takes n number of type int as argument and returns two int values. The return values are filled in the calling function in a parallel assignment.
Go function multiple return example
package main
import (
“fmt”
)
func main() {
fmt.Println(addAll(10,15,20,25,30))
}
func addAll(args … int)(int,int) {
finalAddValue:=0
finalSubValue:=0
for _,value := range args{
finalAddValue += value
finalSubValue -= value
}
return finalAddValue,finalSubValue }
Output:
100 -100