Functions in Golang

In the previous tutorials, we discussed basic programming like understanding loops or conditional statements, declaring variables or constants, etc. In all programs used to understand the concepts, we used a function. The function name is main, represented as main ( ). Here in this tutorial, you will learn about the types of functions, how to create a function, its return type, etc.

What are the functions in Golang?

In Golang the execution of a program begins with the main function represented as func main ( ).

GO : Functions

A function is a set of similar statements or logical statements that are grouped together. Consider a simple daily example of making tea. In order to make tea, you need to follow a set of instructions like 

  • Take a glass of water
  • Add sugar & tea leaves
  • Add milk
  • Let it boil till tea is ready 
GO : Functions

So if we consider making a tea as a function with the above-mentioned steps as statements or instructions that need to be executed in a grouping fashion, all these statements will be executed together at each time. There may be some variation to these statements (steps) if some extra ingredients are added to the tea while preparing like ginger or cardamom etc. These variables can be input into the function. We will look at this part of how to pass those inputs and change flow in the functions incoming section of this tutorial.

How to declare a function in Golang?

In Golang to declare a function, you should use the keyword func

  • The keyword func is followed by a name of the function which will be uppercase letters (capital) or lowercase letters (small) depending on the access level. 
  • If the function name begins with a capital letter as the first character then the function will have a public scope & can be accessed from other packages. 
  • After the name, there is a parenthesis ( ) that contains all the input parameters that are needed to supply to the function to change the flow of the function. 
  • Then comes an open curly bracket “{“to start and at the end a curly bracket to close the function “ } “.
     

Syntax to declare a function


func name(parameters){
    body of statements
}

Where

  • func is function keyword
  • name is the function name
  • The parameter is the arguments passed to the function may be single or multiple arguments with a return type or not.
  • The curly { } braces enclose the function body which executes when the function is called.
     

Note: Need to be careful that the open curly bracket should be in the same line where the name of the function is declared, it cannot be in another line.

In go language, it is not allowed as in many other programming languages. Let us see a simple program


package main
import ("fmt")

// main function
func main()  {
  fmt.Println("I am main function ")
}

Output:


I am main function 

How to call a function in Golang?

Let us understand the concept of calling a function with the classic hello world program. Let us introduce a function hello, hello() by using above explained syntax.


func hello() {
    fmt.Println("Hello, World!")
}

Golang function with empty parentheses

GO : Functions

We have created a function hello (). If you run this code inside a Go program it will not execute inside the program because our function is not fully defined. In order to execute and print or display the output, we need to call the function inside the main ( ) function of our program.

Let us see how to call the function hello() inside of our main() function block.

The program begins its execution from the main () function. The main() function appears only once in any program with package main which receives & returns no arguments. The below example shows the fully executable code that calls function hello() inside main()
Program to call a function


package main
import "fmt"

func main() {     //main  function
    hello()       //calling user defined function named hello
}

func hello() {   //created function hello 
    fmt.Println("Hello  World!")
}

Output:


Hello, World!

How to call a function with arguments in Golang?

In the previous section, we discussed calling a function with empty parentheses. Let us learn how to use parameters inside a defined function parentheses. While defining arguments inside parentheses need to specify its corresponding data type too.
Golang function with arguments inside parentheses

GO : Functions

Let us understand with the below example program. The program has a functioning site () with two parameters defined within parentheses. The first argument is of string data type called name and the second argument is of integer type called rept. When the function site ("Learn eTutorials", 5) is called the control goes to func site where the set of instructions to be executed during the site function call is defined. The instruction provided inside the body is a for loop which loops the name 5 times.


package main
import "fmt"

func main() {
    site("Learn eTutorial", 5)  // calling function with two parameters
}

func site(name string, rept int) {
    for i := 0; i < rept; i++ {
        fmt.Print("\n ",name)
    }
}

Output:


 Learn eTutorial
 Learn eTutorial
 Learn eTutorial
 Learn eTutorial
 Learn eTutorial

What is the function return type in Golang?

In Golang, functions can have any return type with any type of argument enclosed within function parenthesis. Let’s see how to declare a return type of function.
Syntax with return type


func name(parameters) <datatype of return type>{

    body of statements
}

In the above syntax, the keyword func defines a function followed by a function name with arguments or parameters enclosed within parenthesis till now is similar to the normal function declaration. In this syntax, we have mentioned a new thing that is the,return type of function which can be int, float, a string of any data types we have discussed in basic data types.

GO : Functions

let us understand with a program


package main
import "fmt"

func add(x int, y int) int {     //add function

    return x + y
}

func sub(x, y int) int {       //sub function of omit type

    return x - y
}

func main() {

    fmt.Println(add(10, 5))     //calling function add
    fmt.Println(sub(10, 5))    // calling function sub
}

Output:


 15
 5

Note: When the function parameters have the same datatype, that type can be omitted for one of the parameters, it is known as omit type

In the above program add () and sub() are two functions with two parameters of integer type. In add (),x & y are arguments of integer data type specified separately as int x, int y inside parentheses. In sub(), two arguments x & y are of integer type but only one argument is specified with the datatype. In such a case if both arguments have the same data types we can omit defining either of the argument data types.

GO : Functions

 It is understood in such a definition style the argument without datatype has a similar datatype of another argument mentioned inside parentheses. The type is omitted for variable x.

Named return variables of function in Golang

In Golang after function parameters, along with return type of function, named return variables can also be specified.

GO : Functions

Let us understand with a program


package main
import "fmt"

func add(x int, y int) (a int) {     //add function with return type variable a
   a = x + y
    return 
    
}

func sub(x, y int) (b int) {       //sub function of omit type & return variable b
 b = x - y
    return 
}

func main() {
    fmt.Println(add(10, 5))     //calling function add
    fmt.Println(sub(10, 5))    // calling function sub
}

Output:


 15
 5

The above given code declares named variables a & b of integer type with respective add() and sub() functions. The calculation corresponding to each function is stored in variables and is returned with values using the return keyword. Once the main() function starts executing, calls the functions and displays the output as shown above.

Note: From the above programs we understood Golang supports multiple arguments in a function. Inside the function parenthesis, more than one argument can be passed.

Naming convention in Golang Functions

  • A function name must begin with a letter and can have any number of additional letters and numbers.
  • The function name cannot start with a number.
  • Spaces are not allowed in the function name.
  • The keyword func is followed by a name of the function which will be uppercase letters (capital) or lowercase letters (small) depending on the access level. 
  • If the function name begins with a capital letter as the first character then the function will have a public scope & can be accessed from other packages. 
  • If a name consists of multiple words, each word after the first should be capitalized like this: empName, EmpAddress, etc.
  • case-sensitive (add,ADD,Add are three different variables).
     

What are Anonymous Functions in Golang?

A function declared without any named identifier to refer to it is known as an anonymous function. Anonymous functions accept inputs and return outputs, similar to standard functions.
Program anonymous function


package main
import "fmt"

var (
   add =func(x int, y int) (a int) {     //add function with return type variable a
  a=x + y
    return 
}
)
func main() { 
    fmt.Println(add(10, 5))     //calling function add
    
}

Output:


 15