Wednesday, November 14, 2018

Learn Golang Tutorials - Beginner guide to Functions with examples

Learn Golang Tutorials - Beginner guide to Functions with examples

Golang Functions

This article covers the following things related to functions in  Go language 
  • why Function are 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 code written to achieve specific functionality. every functionality is defined as a function in Go Langauge.
Every Runnable code in golang has main() function.k The functions can be called by some other code at a different location. The advantages with 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 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, 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 function name which is being used to execute by the caller in other location code base 
  • argument1 -  These also called parameter, 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 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 is 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

Example

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

Empty Function declaration

The following is an empty function which has no input parameters and it is not returning anything. This is also a valid function.
func printmessage() {  
 fmt.Println("Hello world")
}
Basic Function with input and output here is an example for 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))

}
We have declared a function. Now we have to call the function. the function is called with function name by giving function parameters. the syntax is sum(1, 2) and 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 functions 

In Other programming languages like Java and javascript always returns a single value. Functions in Golang returns 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 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 of below code where return types are not declared in ( and ). It gives compilation error missing function body, 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 the 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 as a blank identifier. on which any type of value accepts and not returned from 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 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 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 return statement must be declared with new variable
func Increment(value1 int) (v1 int) {
 var v2 = value1 + 1
 return v2
}
The following code is not valid as 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 

This is one more feature of a function in golang. Function can be declared with variable number arguments. Println is inbuilt in function which accepts 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 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 

Golanguage supports function declared without a name. These are called anonymous functions in other programming languages in java and javascript. closure is one type of anonyms functions that can access the variables defined outer function itself. We will see various examples of this two features Function can be used as value and assigned to variable Here function without is declared and assigned to variable, This is being called in other place using variable name with ( and )
var functionName = func() string { // this assigns anonymous function to variable
 return "testvalue"
}

func main() {
 fmt.Printf("%s", functionName())
}
output is
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 function, In the following example, Function2 is declared with function argument This function2 is called with supplying 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 is
9
Closure with nested function 
a function declared inside other function, 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 is
6
18

defer statement 

defer is a keyword which is used as a statement in language. Defer is used in function as its execution before function return its value. defer logic always executes before declared function returns its value. defer keyword is declared before a function is declared of a outer function
package main

import "fmt"

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

}
output is
25

arrays as slice of arguments 

Functions can be passed with an array as an argument, Instead of declaring an array in the function declaration, We can slice the array Function declaration 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 is
10
Conclusion
Like every programming language, Functions are building blocks and most useful in go language. There are lot features that functions supported in this language.

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

Related article


EmoticonEmoticon