Function in GoLang
Function
What is a function in GoLang?
function is a self-contained block of code that encapsulates a specific task or related group of tasks.
Function Syntax
func function_name( [parameter list] ) [return_types] {
body of the function
}
Function Example
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
var b int = 200
var ret int
/* calling a function to get max value */
ret = max(a, b)
fmt.Printf( "Max value is : %d\n", ret )
}
/* function returning the max between two numbers */
func max(num1, num2 int) int {
/* local variable declaration */
var result int
if (num1 num2) {
result = num1
} else {
result = num2
}
return result
}Output
Max value is : 200Function Return Multiple Values
GoLang function can return multiple values.
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("Nitish", "Kumar")
fmt.Println(a, b)
}Output:
Kumar NitishFunction as Values
Get Nitish Sharma’s stories in your inbox
Join Medium for free to get updates from this writer.
GoLang function can be assigned to variables and passed to or returned from other functions.
package main
import "fmt"
func main() {
/* declare a function variable */
getSquareRoot := func(x float64) float64 {
return math.Sqrt(x)
}
/* use the function */
fmt.Println(getSquareRoot(9))
/* create a slice of functions */
funcArr := []func(float64) float64{
getSquareRoot,
getSquareRoot,
}
/* call every function */
for i, funcVal := range funcArr {
fmt.Printf("Calling function at index %d returns %.2f\n", i, funcVal(9))
}
}Output:
3
Calling function at index 0 returns 3.00
Calling function at index 1 returns 3.00Function Closure
GoLang function can be nested and they have access to variables declared in the outer function.
package main
import "fmt"
func getSequence() func() int {
i:=0
return func() int {
i+=1
return i
}
}
func main(){
/* nextNumber is now a function with i as 0 */
nextNumber := getSequence()
/* invoke nextNumber to increase i by 1 and return the same */
fmt.Println(nextNumber())
fmt.Println(nextNumber())
fmt.Println(nextNumber())
}Output:
1
2
3Function Methods
GoLang does not have classes. However, you can define methods on types.
A method is a function with a special receiver argument.
The receiver appears in its own argument list between the func keyword and the method name.
In this example, the Abs method has a receiver of type Vertex named v.
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := Vertex{3, 4}
fmt.Println(v.Abs())
}Output:
5







