Go functions

Golang functions

A go function is a group of statements that can perform a specific functionality for different data values.

Go function with return type

Example: Find maximum of two given numbers.

package main

import "fmt"

func main() {
   a, b, c, d := 1, 2, 3, 4
   result1 := max(a, b)
   fmt.Printf("Max value is : %d\n", result1)
   result2 := max(c, d)
   fmt.Printf("Max value is : %d\n", result2)
}

func max(num1 int, num2 int) int {
   if (num1 > num2) {
      return num1
   } else {
      return num2
   }
}

Output:

Max value is : 2
Max value is : 4

If you see the above we have used the function twice for different values.

Go function without return type

We can write go functions that return no values but performs some operations.

Example: Greet user

package main

import "fmt"

func greetUser(user string){
    fmt.Printf("Hello %s\n", user)
}

func main() {
   user := "Anji"
   greetUser(user)
}

Output:

Hello Anji

If we see the above function greetUser, we not returning any data. That's reason we didn't specify the return type.

Go function that return multiple values

We can return multiple values in go functions.

Example: Find rectangle area and perimeter

package main

import "fmt"

func rectangle(l int, b int) (area int, perimeter int) {
    perimeter = 2 * (l + b)
    area = l * b
    return // Return statement without specify variable name
}

func main() {
    var a, p int
    a, p = rectangle(20, 30)
    fmt.Println("Area:", a)
    fmt.Println("Perimeter:", p)
}

Output:

Area: 600
Parameter: 100

Go Variadic Functions

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

Example: Find sum of all given numbers

package main

import "fmt"

func sum(nums ...int) {
    fmt.Print(nums, " ")
    total := 0
    for _, num := range nums {
        total += num
    }
    fmt.Println(total)
}

func main() {

    sum(1, 2)
    sum(1, 2, 3)

    nums := []int{1, 2, 3, 4}
    sum(nums...)
}

Output:

[1 2] 3
[1 2 3] 6
[1 2 3 4] 10

If you see the above function we have sent 2 arguments and 3 arguments respectively and we got the results in both of the cases. This type of functions are called as variadic functions.