Function

In previous examples, I have a lot of code which is in a function calling main. Thats’s right, because program in golang start with main function in main package. That mean when you run a golang program, it find main package and run main function. And you can not code a lot of thing only into main function. What we need to do with a big program with many and many code lines. Using function to split our program, that is answer. Functions are central in Go. We’ll learn about functions with a few different examples.

Basic function in Golang

Do declaring function in Golang, you use this common syntax

This is an example for plus function. In the same file with function main of program

First, you declare a function with name “plus”, this function get 2 params “a” and “b”, integer data type. Use “+” to plus a and b, assign result for c and return c for plus function. Nice

Continue with function “plusplus”, 3 params(because a, b, c is the same data type, so you can omit data type in params), return a + b + c

Good job, and try calling 2 functions in main.

There are several other features to Go functions. One is multiple return values, which we’ll look at next.

func functionName(param1 dataType, param2 dataType, ...) returned_dataType {
 content of function here
return result
}
package main

import "fmt"

func plus(a int, b int) int {
    c := a + b
    return c
}

func plusPlus(a, b, c int) int {
    return a + b + c
}

func main() {
    res := plus(1, 2)
    fmt.Println("1+2 =", res)

    res = plusPlus(1, 2, 3)
    fmt.Println("1+2+3 =", res)
}

Multiple return value function in Golang

If you want to return many result in one function, Golang support multiple returned retults for it. This feature is used often in idiomatic Go, for example to return both result and error values from a function.

In this example, I create function “NotZero” get a param “a” is integer and return 2 values (boolean and error object). If a is 0, I should return false and error. If not, that’s true and nil error

Because our function return 2 values, so, you need to use 2 variables to get those 2 value

If you only want a subset of the returned values, use the blank identifier _.

package main

import (
"fmt"
"errors"
)

func NotZero(a int) (bool, error) {
    if a == 0 {
       return false, errors.New("value is zero")
    }
    return true, nil
}

func main() {
    ok, err := NotZero(0)
    if err != nill {
      fmt.Println(ok)
    } else {
      fmt.Println(ok)
    }

   _, err = NotZero(1)
   fmt.Println(err)
}

Accepting a variable number of arguments is another nice feature of Go functions; we’ll look at this next.

Variadic Functions in Golang

Variadic functions can be called with any number of trailing arguments(with the same data type). For example, fmt.Println is a common variadic function.

Here’s a function that will take “nums” is param and nums is …int

.

.

.

That mean you can pass many integer value into function.

Variadic functions can be called in the usual way with individual arguments.

You can use slice as param for Variadic functions by use “sliceVaruable” to pass it as a param

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...)
}

View on github

PreNext