Functions in GO Tutorial

Udemy Generic 728x90

Objective

To understand, how to write functions in Go Lang.

 

A function is a block of code which execute to execute some specific commands and tasks.

You can divide your bulk of code in function. To perform a task through function you have to correctly declare the function with its definition. Declaration of a function tells the compiler about the function parameters, name, return type. Definition is the actual body which executes on call.

Like C, In GO language functions starts with the func keyword. And type comes after the variable name. You can use golang package function which is predefined or create your own.

Step 2

Create a user defined function in GO lang

Syntax :


    func functionName(varName type){
        // code to be executed;
    }

To create a function you have to start with the keyword func then name of the function you want to create. Then in parenthesis front of the function name you have to put the list of variables.

For each variable you have to write a variable name first and its type next to it.

In go language. if two or more consecutive variable have same types then you can omit type from all the variable name except the last.


    func add(x, y int) int {
        return x + y
    }

Now, if you want return in something from function then you need to customize the main syntax. For this you need to add the return type after the variables.


    func functionName(varName type) (string) {
	return Strings.Title(varName)
    }

In go lang function can return multiple variable so,  if you are returning the two variables, then you have to put return type in the order according to the returning variables


   func functionName(varName type) (string, int) {
	return Strings.Title(varName), len(varName)
   }

Function containing the return type must have return function otherwise it will throws error.

Step 3

Calling a function

To call a function, simply call the function by its name

                                       functionName(“Vishal”)

If function is returning something, set the variable name in which return value have to be store

                                    name  = functionName(“Vishal”)

                                                      or

                                    name, size  = functionName(“Vishal”)

If you don’t have to store the value in any variable, then you can simply put underscore at the place of variable name. So that golang put your return value in trash can.

                                    name, _ = functionName(“Vishal”)

 

Udemy Generic 728x90

Spread the word. Share this post!