Golang Tutorials - Beginner guide to Functions with examples

Golang Functions introduction

This article covers the following things related to functions in Go language

  • Why Function is required?
  • Function Declarations
  • Multiple return values
  • Named return values
  • Defer
  • closure
  • Anonymous functions
  • The function assigned as the value
  • passing arguments to the function
  • Function slice to an array

Why Function is required?

Functions are a program or multiple lines of code written to achieve specific functionality. Every functionality is defined as a function in Go Langauge.

Every Runnable code in golang has a main() function.The functions can be called by some other code at a different location. The advantages of functions are duplicate code and maintenance of code. Few key points of a function in golang.

  • Functions are code statements designed to achieve some tasks
  • It takes input and executes the code and returns the output
  • Functions are executed when functions are called by some other code
  • functions are also called subprograms, methods, procedures

The syntax for defining functions:

func functionname([argument1 datatype,argument2 datatype])[returnvaluename returntype]{
code block statement(s)
}

To design functions in any programming language, the following things are required

  • Function Header
  • Function Body
  • Function Caller

Function declaration contains header and body.

Few notes about the syntax of the function.

  • func keyword: func is a keyword in golang. Every function declaration always starts with this keyword.
  • functionname : It is a function name that is being used to execute by the caller in other location code base
  • argument[1,2] : These are also called parameters, which will be enclosed with ( and ). The syntax for argument declaration is the argument name followed by data type. Multiple parameters can also be declared separated by a comma. These are optional ie empty parameters are also valid.
  • return type: Function return multiple values. Declaration of return type contains name and type. Type is optional. Any number of return types can be declared. It is an optional type.
  • Function body: It is actual code written to achieve some tasks which are placed between { and }
  • Function caller: Once the function is declared, we need to execute a function by calling it. Once the function is called, control goes to function body and executes it and return the value, once done, control transfer to caller code

Golang Function Example

We will see various features of functions with various and examples in the below sections.

Using Empty Function declaration

The following is an empty function that has no input parameters and is not returning anything.

This is also a valid function.

func printmessage() {
 fmt.Println("Hello world")
}

Basic Function with input and output paramters:

Here is an example for the function

The below function has two input parameters - value1 and value2 of data type int. The return type is also int which returns the sum of these two numbers.

package main

import "fmt"

func sum(value1 int, value2 int) int {
 return value1 + value2
}
func main() {
 fmt.Println(sum(1, 2))

}

After, Function is declared, call the function. The function is called with function name by giving function parameters.

the syntax is sum(1, 2), the output of the above program is

3

Multiple parameters of the same type:

When there are multiple parameters of the same type are declared side by side, We can avoid by declaring type multiple times with simple syntax as follows.

func sum(value1, value2 int) int {
 return value1 + value2
}

Return Multiple values from a function

Other programming languages like Java and javascript always return a single value.

Functions in Golang return multiple values.

  • Declared IncrementAndDecrement function with two parameters of the same type,
  • first parameters is incremented by one, the Second parameter is decremented by 1.
  • Finally, both return the values. If the function is returning multiple values, return types must be declared with ( and ). Return types in header and body are separated by the comma
func IncrementAndDecrement(value1, value2 int) (int, int) {
 var incrValue = value1 + 1
 var decrValue = value2 - 1
 return incrValue, decrValue
}
func main() {
 value1, value2 := IncrementAndDecrement(5, 5)
 fmt.Printf("%d  %d", value1, value2)
}

The output of the above program code is

6 4

Please have a look at the below code where return types are not declared in ( and ). It gives compilation error missing function body, the unexpected comma after the top-level declaration, non-declaration statement outside the function body

func IncrementAndDecrement(value1, value2 int) int, int {
 var incrValue = value1 + 1
 var decrValue = value2 - 1
 return incrValue, decrValue
}
func main() {
 value1, value2 := IncrementAndDecrement(5, 5)
 fmt.Printf("%d  %d", value1, value2)
}

The complete error report is

A:\Golang\work>go run First.go
# command-line-arguments
.\First.go:5:6: missing function body
.\First.go:5:51: syntax error: unexpected comma after top level declaration
.\First.go:8:2: syntax error: non-declaration statement outside function body

Blank Identifier - subset return values

We already saw multiple return values support in golang. the function is returning two values, the caller has to get only a subset of data ie one value should be returned from the function. Then we will use the blank identifier for this. _ is called a blank identifier. on which any type of value accepts and not returned from the function The IncrementAndDecrement function returns two values, But the caller needs only one value, Another value place should be replaced with a blank identifier (_)

package main

import "fmt"

func IncrementAndDecrement(value1, value2 int) (int, int) {
 var incrValue = value1 + 1
 var decrValue = value2 - 1
 return incrValue, decrValue
}
func main() {
 _, value2 := IncrementAndDecrement(5, 5)
 fmt.Printf("%d", value2)
}

Output is

4

Named return values from a Function

In all the above examples, We are just providing return type in the function declaration. We can also provide return name and type.

In the below function declaration, the returned statement contains name and type and both are enclosed in ( and )

func Increment(value1 int) (v1 int) {
 v1 = value1 + 1
 return v1
}
func main() {
 value1 := Increment(5)
 fmt.Printf("%d", value1)
}

valid cases for multiple values return for the above code.

It is not required to return the value manually. Just a return statement is enough.

named return value(v1) in declaration ie (v1 int) and body ie.v1 = value1 + 1 should have same name for this case

func Increment(value1 int) (v1 int) {
 v1 = value1 + 1
 return // not required to have return value
}

This is also valid as named value v1 is different from v2, but the return statement must be declared with a new variable

func Increment(value1 int) (v1 int) {
 var v2 = value1 + 1
 return v2
}

The following code is not valid as the return statement in the header is missing ( and ) and it gives compilation error - missing function body syntax error: unexpected int after top-level declaration

func Increment(value1 int) v1 int {
 v1 = value1 + 1
 return v1
}

Variadic functions - variable arguments

It is one more feature of a function in golang. The function can be declared with variable number arguments. Println is inbuilt in function which accepts a variable number of arguments.

the syntax for this function declaration

func functionname (arguments ...datatype)

These functions are declared with ellipse (three dots ) in the arguments. This should be declared as the last argument.

package main

import "fmt"

func IncrementAndDecrement(nums ...int) int {
 result := 0
 for i := range nums {
  result += nums[i]
 }
 return result
}
func main() {
 res := IncrementAndDecrement(5, 5)
 fmt.Printf("%d", res)
 res1 := IncrementAndDecrement(5, 1, 7)
 fmt.Printf(" %d", res1)
}

and the output is

13

The below code gives compilation error - can only use … with final parameter in list numbs arguments are not final or last arguments of the function declaration.

func IncrementAndDecrement(nums ...int, string s) int {
 result := 0
 for i := range nums {
  result += nums[i]
 }
 return result
}

Closure or anonymous functions

Go language supports function declared without a name. These are called anonymous functions in other programming languages such as java and javascript.

The closure is one type of anonyms function that can access the variables defined outer function itself.

Let’s see various examples of these two features.

Function can be used as value and assigned to variable :

Here function without name declared and assigned to a variable, This is being called in other place using a variable name with ( and )

var functionName = func() string { // this assigns anonymous function to variable
 return "testvalue"
}

func main() {
 fmt.Printf("%s", functionName())
}

output:

testvalue

Anonymous functions with inline arguments The above function can be written in another way by appending argument value inline using ( and )

func main() {
 //Anonymous functin assined to variable by appending argument value inline
 var functionName = func(s string) string {
  return "testvalue " + s
 }("cloudhadoop")
 fmt.Printf("%s", functionName)
}

output is

testvalue cloudhadoop

passing function as an argument :

The function can also be passed as an argument to other functions.

In the following example, Function2 is declared with function argument. This function2 is called with supplying an argument

func funciton1(value int) int {
 return value * value
}
func funciton2(functionargument func(int) int) int {
 return functionargument(5)
}
func main() {
 fmt.Printf("%d", funciton2(funciton1))
}

Output is

25

Return type as a function from other function:

Function declaration contains return type as anonymous function declaration function1 is declared with return type as an anonymous function with argument and return type. Function caller should be two parameters enclosed ( and ) separately. Here closure applied as accessed value1 variable inside an inner anonymous function

func function1(value1 int) func(int) int {
 var result = func(value2 int) int { return value1 + value2 }
 return result
}
func main() {
 fmt.Printf("%d", function1(4)(5))
}

Output:

9

Closure with nested function:

A function declared inside other function called nested functions. Outside function variables are accessed inner function.

Nested function is declared inside the main function. fmt class is being declared in the main function and accessed inside nested function value2 is declared in the main function and being accessed in nested function

func main() {
 var value2 = 12
 var nestedFunction = func(value int) int {
  fmt.Println(value)
  return value + value2
 }
 fmt.Println(nestedFunction(6))
}

and output :

6
18

defer statement in functions

defer is a keyword that is used as a statement in language.

Defer is used in function as its execution before the function returns its value. defer logic always executes before the declared function returns its value.

defer keyword is declared before a function is declared of an outer function

package main

import "fmt"

func myfunction() (value int) {
 defer func() {
  value = 25
 }()
 return value
}
func main() {
 fmt.Println(myfunction())

}

output is

25

How to pass arrays as a slice of arguments to Functions in Golang

Usually, Functions declared array in declaration to pass array as an argument. Instead of passing an array, We can slice the array to Function declaration which accepts variable arguments using ellipse symbol- function caller accepts slicing arrays like myfunction(array1...)

func myfunction(params ...int) int {
 result := 0
 for _, value := range params {
  result += value
 }
 return result
}
func main() {
 var array1 = []int{1, 2, 7}
 fmt.Println(myfunction(array1...))

}

And output:

10

Conclusion Like every programming language, Functions are building blocks and are most useful in go language. There are a lot of features that function supported in this language.

Please share your valuable comment or feedback and share it on Social Media.