Friday, July 24, 2015

An Introduction to Go Functions with Examples

Why Functions?

Go Functions has same use as functions in any other language. They serve as basic building blocks of a software program. You can break a big problem into various smaller chunks i.e. functions which can be called wherever required i.e. you can avoid redundant code. 

If you are not that rare someone from the WET (We Enjoy Typing) camp you must be someone who is happy to follow the DRY (Don't Repeat Yourself) principle. Functions facilitate code reuse and are thus compatible with DRY.

If you're already familiar with the basic of functions you can read the next articles of the series:

Let us try a simple function. In the following example we've defined a function named test() which is getting called in the main() function. You can play with the code here

Example# 1

Output of example# 1

Example# 2
Play here 

You can copy the below code, it's not an image:

package main

import "fmt"

func main() {

 funcWithoutParam()//Calling a function that has no parameter
 //r is an argument, is passed to funcWithParam
 r := "hello from a function with a parameter!"
//Function without a parameter
 func funcWithoutParam() {
 fmt.Println("hello from a function without a parameter!")
//Function with a parameter
 func funcWithParam(p string) string {
 return p

Output of example# 2
hello from a function without a parameter!
hello from a function with a parameter!

What's the difference between Example#1 and Example# 2

Example# 1 has a function named test() that has no parameters. Example# 2 has two functions, one with parameter and another without any parameter. 

What's the difference between a Parameter and an Argument?

A parameter is the variable which is part of the function's signature. See example# 2:

               func funcWithParam(p string) string 

Here, the variable p is a parameter.

Whereas an argument is the real value/data that is passed to the function when calling it. See example# 2,: 
r := "some string text"
func funcWithParam(r)

As we tend to learn quick by examples here are a few more examples of function:

Addition of Two Numbers

Example# 3



Function to find Odd or Even Numbers using Modulo Operator

Example# 4
Play here 
Output Example# 4

Example# 5
Function to find Odd or Even Numbers using Bitwise Operator
Play with the code

You can copy the below code, it's not an image:

package main

import "fmt"

func isEvenOdd(x int) string {

 if (x & 1 == 0) {
 return "even"
 } else {
 return "odd"

func main() { 
 var i int
 fmt.Println("Enter an Integer")
 fmt.Scanf("%d", &i)

The output of example# 5 is same as example# 4.

Additional Information

Do you want to know what's the precise difference between a Function and a Method? Read this post Go Methods to understand it.

Bitwise Operator to find Even or Odd Number

With reference to the code example# 5 many of you who are new to programming may not have understood the logic behind the code. It's a bit tricky for beginners but it is simple. Let us try to understand:

In natural languages, when we count we use base 10 i.e. to form a number we use any of the digit starting from 0 to 9 (i.e. we have 10 options). We call this system as Decimal Numbers.

Computer DOES NOT understand natural language i.e. Decimal Numbers. It understands only two numbers 0 and 1 or numbers formed by combination of these two numbers. We call this system as Binary Numbers.

Decimal           Binary
0                          0
1                      001
2                      010
3                      011
4                      100
5                      101
6                      110
7                      111

If you notice carefully the binary equivalent of any Odd number (marked in blue font) has 1 at the right most position. The Even numbers (marked in black font) have 0 as the right most position.

Important Note:

Bitwise & returns a one in each bit position for which the corresponding bits of both operands are ones.

We've used Bitwise & operator as follows:

if (x & 1 == 0)

Now let us decipher the above line of code. 

Suppose x is 4. Now the system internally translates the above line to:

if (100 & 001 == 0)

As the rightmost digits of the above comparison are 0 and 1, hence the output of a bitwise & operation will be 0, it means the if condition is true. So the function will return "even". 

Suppose x is 5.  Now the system internally translates the above line to:

if (101 & 001 == 0)

As the rightmost digits of the above comparison are 1 and 1, hence the output of a bitwise & operation will be 1, it means the if condition is false. So the function will return "odd". 

Can you alter the if condition by comparing x with 0 or by equating x & 1 with 1?

Here's a good codecademy beginners level tutorial [FREE] if you want to learn more about bitwise operators.

Did you like this? Please share and let me know if I can improve this to make it more beginner friendly.

Monday, July 13, 2015

Go Structs

The developers who don't like OOP and are yet to figure out the precise difference between a class & object can breath easy now. 

Go has got rid of Classes.

Is Go an Object Oriented Language?

Before you read my version, Find the official answer here. In a strict sense, personally I believe that Go doesn't have the essential attributes to be called an OOP language. Go doesn't have the concept of Object, Inheritance Polymorphism. Does this make things simple? You may choose to differ but I think, Yes it does. That's one of the various reasons I like Go - it's simple & yet so powerful. 

What are Structs?

Go has structs which are behaviorally similar to classes and can be associated with Methods. Struct is a custom type which represents a real world entity with its properties, and each property may have its own type. 
  • Structs are value types.
See the following code sample where a struct named Person has 2 fields (properties) - name of type string and age of type int.


package main
import "fmt"

type Person struct {
 name string
 age  int

func main() {
 p := Person{}
 fmt.Println("Default values for Person is: ", p)

Output RefCode#1.1

Default values for Person is:  {0}

Play with the above code

As we've not provided any value to the struct fields name and age the output is initialized with default values i.e. empty string or zero; depending on the data type of the fields.

Another sample RefCode#1.2

package main

import "fmt"

type Person struct {
 name string
 age  int

func main() {
 p := Person{"Steve", 56} // assign value in the order in which they are defined
 fmt.Println("Person's name & age is: ", p)

Output RefCode#1.2

Person's name & age is:  {Steve 56}

Play with the above code

In the following code, we've provided a value that is reflected in the output.
sample RefCode#1.2 can be rewritten as:

Sample RefCode#1.3

package main

import "fmt"

type Person struct {
 name string
 age  int

func main() {
 p := Person{age: 56, name: "Steve"} //assign value by variable name and :
 fmt.Println("Person's name & age is: ", p)
 fmt.Println("Person's age is: ", p.age)

The output of the above sample:

Person's name & age is:  {Steve 56}
Person's age is:  56

Play with the above code.

If you've observed the above code samples carefully you might have noticed how a struct is initialized. If you're new to programming you can read the following section.

Initialization of a Struct

An instance of type person can be created by any one of the following two ways:

1. var p Person
--- This creates a local person variable with default values set to zero i.e. age = 0 and name = ""  

"" represents empty string

2. p := new(Person)

This allocates default values for the struct fields age and name. It returns a pointer. 

Assigning Values to Struct Fields

Use any of the two ways described below:

1. p := Person{age: 29, name: "Basant"} 

        --- You can change the order of the fields, can also be written as follows:
        p := Person{name: "Basant", age: 29}

2. p := Person{29, "Basant"}

        --- You must know the order of the field and maintain it. 

Accessing Struct Fields

Fields are accessed using the . operator (dot operator).

fmt.Println("Person's age is: ", p.age)

The above line of code is used in  RefCode#1.3.

Did you like this? Is it beginners friendly? Please spread the word about it.

Thursday, July 9, 2015

Formatting Go Code with Gofmt Tool

My Code Format/Style is Better than Yours

How many times have you experienced a cold war like situation in your team because each one of you have your own way to format code when it comes to indentation, spacing and brace positioning?

Go has Only One official Style & that is Enforced

Go designers have taken care of this and have come up with a tool named Gofmt that can format Go code in the official way :) Now there's no more:

  • debate over spacing, indentation and brace positions.
  • worries about minor formatting while writing code.
  • worries about converting someone's else's formatting style to your own to make the code more readable.

Here's a sample of a code that is working but is not formatted well.

shabbily formatted Go code. Also notice extra braces in Printf

Above go code file named gofmt.go is a working code where the developer has not taken care of the spacing, see { in line#3; has placed unnecessary braces, see line#4. Also there's no white-space between package, import and func, see line# 1, 2 and 3. 

How can we format this code using this tool named Gofmt?

Let us run the following Gofmt command:

The command is simple, gofmt -w <name of your go file>. Incidentally in the above example the file name is also gofmt.go, please don't get confuse. You can name it the way you like, a name that best describes your file. 

Now let us see the result of above command. The output, in the following image, looks more readable than the previous image.

We still have extra braces in Line# 6
If you carefully observe the above image, we still have a pair of extra braces in line# 6. To explicitly remove them we can use the following command:

For your implementation the only thing which changes here is the name of the go file, rest you can keep same. The following output now looks neat and well formatted as expected. 


Try what happens when you type the following command.

1. gofmt filename.go
2. gofmt filename.go > newfilename.go
3. Can you use the gofmt tool to format all the go files inside a directory via a single command?


1. This will print the reformatted code but won't change the source file. If you want to change the source file you must introduce the flag -w , something like, gofmt -w filename.go (already shown, the 1st command of this post).

2. This will write the formatted code of source file filename.go into a new file named newfilename.go in the same directory.

Currently, I'm using LiteIDE and I'm happy to see that it already has Gofmt tool available from the toolbar as a menu option (Build > Gofmt). So there's an option for using Gofmt from the UI as well.

3. Yes. The same command that we used for files works for directory as well. We simply need to provide the directory path. It will be:

gofmt -w DirectoryPath. 

Example, if you've 3 files in a directory named src inside go directory in C drive and you want to format all of them in one shot, then you simply need to issue the following command:

gofmt -w go\src