by- Kabeer Shaikh

Originally published at RemotePanda Blogs

As we have covered Golang ‘language fundamentals’ in our Third Chapter, let’s explore ‘Control Flow’ and ‘Functions’ in this chapter.

The control flow statements are used to break the flow of execution by branching, looping, decision making statements by enabling program to execute code based on the conditions. All programmers must know the control flows like if-else, switch case, for loop, break, continue, return.

  • if/else
  • if/else if/else
  • if/else if/else if/…../else

The if statement is similar to other programming languages. If statement is expecting some condition and based on the condition it will execute the code.

Note: use else/else if just after closing of if statement’s closing bracket “}“ otherwise you will get compile time error.

For loop

Golang has only one loop which for loop. Like other programming languages it doesn’t have while and do while loop. But we can use for loop as while loop.

Switch case

Most programming languages have switch case to avoid complex if-else-if statements.

  • we can compare only values of same types
  • we can set optional default statement if condition fails
  • we can use expression if need to compare condition based on value to use

“fallthrough” is optional in switch case. This keyword is used in case statement and when it is encountered, it will go to next case even if next case is failing condition. So it is optional in this switch case.

We can specify multiple values in case statement. Also we can return a value based on switch cases.

Normally we switch on value of a variable but Golang allows you to switch on type also.

Functions

Functions are no. of statement that together perform a task and make execution flow more reliable so that we can reuse the code whenever needed.

The execution of Go program starts from the main function itself func main(){ } . A function takes one or more parameters and return one or more outputs. Like other programming languages, go explicitly needs to return values.

The Syntax is

Function starts with keyword func and its name. The parameters need to define like var_name var_type. After this we need to write return type if function is going to return. Writing of function can be difficult so better idea is to break into manageable code, rather that going for full implementation.

Mostly we are returning result along with error like x,err:=func(). Avoid using nameless return.

Variadic Function

This one is special form of function which can take any arguments. It is like varargs in Java. We can pass any number of parameters to the variadic function of same type. To make function variadic you just need to put three dots … before the arguments type. It will allow you to pass any number of arguments to the function.

Here ,you can see how the fmt.Println() is implemented in “fmt” package. func Println(a …interface{})(n int,err error)

So the Println function can take any number of arguments of any type. We can also pass slice of ints for the variadic function.

Function as expression

We can pass function to an expression and call that function by using expression/variable name. This is the only way to have one function inside another.

If you see the type of expression then it will be a func()

No identifier is there and function is anonymous(nameless)

Closure

We can create a function inside functions i.e. nesting of functions.

For this purpose, Go supports anonymous function i.e. function without name which will become local to the function.

Closure helps us limit the scope of variables used by multiple functions. Without closure,for two or more funcs to have access to same variable, that variable would need to be in package scope.

Callbacks

Passing a function as an argument is called callback in golang. Here, we can pass function as an argument.

Here we are passing func call( ) as an argument to the func show( )

Recursion

Recursion is a function which calls itself. It is like two mirrors facing to each other.

  • Recursion will create a stack of function calls every time.
  • Sometimes recursion is the best solutions.
  • Closure and Recursion are the powerful technique of programming which forms functional programming and most of people find recursion difficult to understand than the control flow statements.

Defer

Go has a special statement defer which schedules a function call to execute before function completes.

Defer is used when resources need to be freed away i.e. same like finally block in java which is used to put the resource releasing logic.

For ex. Whenever we open file we need to make sure to close it or while connecting to database after completion of task we need to close the connection.

Advantages→

  • It keeps our Close() near to the Open() and it’s easy to understand
  • deferred func will always run even if runtime panic err occurs

Pass By value

Strictly speaking, there is only one way to pass parameters in Go is Pass By Value. Whenever a variable is passed as a parameter, a copy of that variable is created and passed to the function and this copy will be at a different memory location.

In case, variable is passed as a pointer argument then again new copy of parameter is created and that will point to the same address.

Note that even though func changeIt() changes the name to ‘Rafel’, it does not affect the variable name in main function. This happens because function modifies copy of variable not the original one.

But the func change() is modifying the value because &per and per are two different pointers pointing to same struct which is stored at the same memory address.

Anonymous Function

Anonymous functions are the self-executing functions which are nameless i.e.they do not have name. Only through anonymous function we can do nesting of functions i.e. one function inside another.

Well, we are now all set with major control flows and functions for Golang. In our next chapter, we will explore Golang Data Structures. Make sure you check it out!

About Kabeer Shaikh:

Kabeer Shaikh is a Android Developer At MindBowser Info Solutions

About RemotePanda:

RemotePanda is a personalized platform for companies to hire remote talent and get the quality work delivered from our city Pune. All talents associated with us are close network connections. When we connect them with you, we make sure to manage their quality, their growth, the legalities and also the delivery of work. The idea is to make remote work successful for you.

RemotePanda- Make Remote Work For You

Stay connected with us on Facebook, Twitter, LinkedIn and YouTube

Also, Read our blogs here and watch our webinars.

--

--