How to Download and install GO

Step 1) Go to https://golang.org/dl/. Download the binary for your OS.

Step 2) Double click on the installer and click Run.

Step 3) Click Next

Step 4) Select the installation folder and click Next.

Step 5) Click Finish once the installation is complete.

Step 6) Once the installation is complete you can verify it by opening the terminal and typing This will display the version of go installed

Your First Go program – Go Hello World!

Create a folder called studyGo. In this Go language tutorial, we will create our go programs inside this folder. Go files are created with the extension .go. You can run Go programs using the syntax Create a file called first.go and add the below code into it and save

Navigate to this folder in your terminal. Run the program using the command go run first.go You can see the output printing

Now let’s discuss the above program. package main – Every Go Language program should start with a package name. Go allows us to use packages in another go programs and hence supports code reusability. Execution of a Go program begins with the code inside the package named main. import fmt – imports the package fmt. This package implements the I/O functions. func main() – This is the function from which program execution begins. The main function should always be placed in the main package. Under the main(), You can write the code inside { }. fmt.Println – This will print the text on the screen by the Println function of fmt. Note: In the below sections of this Go tutorial, when You mention execute/run the code, it means to save the code in a file with .go extension and run it using the syntax

Data Types

Types(data types) represent the type of the value stored in a variable, type of the value a function returns, etc. There are three basic types in Go Language Numeric types – Represent numeric values which includes integer, floating point, and complex values. Various numeric types are: int8 – 8 bit signed integers. int16 – 16 bit signed integers. int32 – 32 bit signed integers. int64 – 64 bit signed integers. uint8 – 8 bit unsigned integers. uint16 – 16 bit unsigned integers. uint32 – 32 bit unsigned integers. uint64 – 64 bit unsigned integers. float32 – 32 bit floating point numbers. float64 – 64 bit floating point numbers. complex64 – has float32 real and imaginary parts. complex128 – has float32 real and imaginary parts. String types – Represents a sequence of bytes(characters). You can do various operations on strings like string concatenation, extracting substring, etc Boolean types – Represents 2 values, either true or false.

Variables

Variables point to a memory location which stores some kind of value. The type parameter(in the below syntax) represents the type of value that can be stored in the memory location. Variable can be declared using the syntax Once You declare a variable of a type You can assign the variable to any value of that type. You can also give an initial value to a variable during the declaration itself using If You declare the variable with an initial value, Go an infer the type of the variable from the type of value assigned. So You can omit the type during the declaration using the syntax Also, You can declare multiple variables with the syntax The below program in this Go tutorial has some Golang examples of variable declarations The output will be Go Language also provides an easy way of declaring the variables with value by omitting the var keyword using Note that You used := instead of =. You cannot use := just to assign a value to a variable which is already declared. := is used to declare and assign value. Create a file called assign.go with the following code Execute go run assign.go to see the result as Variables declared without an initial value will have of 0 for numeric types, false for Boolean and empty string for strings

Constants

Constant variables are those variables whose value cannot be changed once assigned. A constant in Go programming language is declared by using the keyword “const” Create a file called constant.go and with the following code Execute go run constant.go to see the result as

For Loop Examples

Loops are used to execute a block of statements repeatedly based on a condition. Most of the programming languages provide 3 types of loops – for, while, do while. But Go programming language supports only for loop. The syntax of a Golang for loop is The initialisation_expression is executed first(and only once) in Golang for loop. Then the evaluation_expression is evaluated and if it’s true the code inside the block is executed. The iteration_expression id is executed, and the evaluation_expression is evaluated again. If it’s true the statement block gets executed again. This will continue until the evaluation_expression becomes false. Copy the below program into a file and execute it to see the Golang for loop printing numbers from 1 to 5 Output is

If else

If else is a conditional statement. The synax is Here the condition is evaluated and if it’s true statements_1 will be executed else statements_2 will be executed. You can use if statement without else also. You also can have chained if else statements. The below programs will explain more about if else. Execute the below program. It checks if a number, x, is less than 10. If so, it will print “x is less than 10” Here since the value of x is greater than 10, the statement inside if block condition will not executed. Now see the below program. In this Go programming language tutorial, we have an else block which will get executed on the failure of if evaluation. This program will give you output Now in this Go tutorial, we will see a program with multiple if else blocks(chained if else). Execute the below Go example. It checks whether a number is less than 10 or is between 10-90 or greater than 90. Here first the if condition checks whether x is less than 10 and it’s not. So it checks the next condition(else if) whether it’s between 10 and 90 which is also false. So it then executes the block under the else section which gives the output

Switch

Switch is another conditional statement. Switch statements evaluate an expression and the result is compared against a set of available values(cases). Once a match is found the statements associated with that match(case) is executed. If no match is found nothing will be executed. You can also add a default case to switch which will be executed if no other matches are found. The syntax of the switch is Here the value of the expression is compared against the values in each case. Once a match is found the statements associated with that case is executed. If no match is found the statements under the default section is executed. Execute the below program You will get the output as Change the value of a and b to 3 and the result will be You can also have multiple values in a case by separating them with a comma.

Arrays

Array represents a fixed size, named sequence of elements of the same type. You cannot have an array which contains both integer and characters in it. You cannot change the size of an array once You define the size. The syntax for declaring an array is Each array element can be assigned value using the syntax Array index starts from 0 to size-1. You can assign values to array elements during declaration using the syntax You can also ignore the size parameter while declaring the array with values by replacing size with … and the compiler will find the length from the number of values. Syntax is You can find the length of the array by using the syntax Execute the below Go example to understand the array Output

Golang Slice and Append Function

A slice is a portion or segment of an array. Or it is a view or partial view of an underlying array to which it points. You can access the elements of a slice using the slice name and index number just as you do in an array. You cannot change the length of an array, but you can change the size of a slice. Contents of a slice are actually the pointers to the elements of an array. It means if you change any element in a slice, the underlying array contents also will be affected. The syntax for creating a slice is This will create a slice named slice_name from an array named array_name with the elements at the index start to end-1. Now in this Golang tutorial, we will execute the below program. The program will create a slice from the array and print it. Also, you can see that modifying the contents in the slice will modify the actual array. This will print result as There are certain functions like Golang len, Golang append which you can apply on slices len(slice_name) – returns the length of the slice append(slice_name, value_1, value_2) – Golang append is used to append value_1 and value_2 to an existing slice. append(slice_nale1,slice_name2…) – appends slice_name2 to slice_name1 Execute the following program. The output will be The program first creates 2 slices and printed its length. Then it appended one slice to other and then appended a string to the resulting slice.

Functions

A function represents a block of statements which performs a specific task. A function declaration tells us function name, return type and input parameters. Function definition represents the code contained in the function. The syntax for declaring the function is The parameters and return types are optional. Also, you can return multiple values from a function. Now in this Golang tutorial, let’s run the following Golang example. Here function named calc will accept 2 numbers and performs the addition and subtraction and returns both values. The output will be

Packages

Packages are used to organize the code. In a big project, it is not feasible to write code in a single file. Go programming language allow us to organize the code under different packages. This increases code readability and reusability. An executable Go program should contain a package named main and the program execution starts from the function named main. You can import other packages in our program using the syntax We will see and discuss in this Golang tutorial, how to create and use packages in the following Golang example. Step 1) Create a file called package_example.go and add the below code In the above program fmt is a package which Go programming language provides us mainly for I/O purposes. Also, you can see a package named calculation. Inside the main() you can see a step sum := calculation.Do_add(x,y). It means you are invoking the function Do_add from package calculation. Step 2) First, you should create the package calculation inside a folder with the same name under src folder of the go. The installed path of go can be found from the PATH variable. For mac, find the path by executing echo $PATH

So the path is /usr/local/go For windows, find the path by executing echo %GOROOT%

Here the path is C:\Go
Step 3) Navigate to to the src folder(/usr/local/go/src for mac and C:\Go\src for windows). Now from the code, the package name is calculation. Go requires the package should be placed in a directory of the same name under src directory. Create a directory named calculation in src folder. Step 4) Create a file called calc.go (You can give any name, but the package name in the code matters. Here it should be calculation) inside calculation directory and add the below code Step 5) Run the command go install from the calculation directory which will compile the calc.go.

Step 6) Now go back to package_example.go and run go run package_example.go. The output will be Sum 25. Note that the name of the function Do_add starts with a capital letter. This is because in Go if the function name starts with a capital letter it means other programs can see(access) it else other programs cannot access it. If the function name was do_add , then You would have got the error cannot refer to unexported name calculation.calc..

Defer and stacking defers

Defer statements are used to defer the execution of a function call until the function that contains the defer statement completes execution. Lets learn this with an example: The output will be Here execution of sample() is deferred until the execution of the enclosing function(main()) completes. Stacking defer is using multiple defer statements. Suppose you have multiple defer statements inside a function. Go places all the deferred function calls in a stack, and once the enclosing function returns, the stacked functions are executed in the Last In First Out(LIFO) order. You can see this in the below example. Execute the below code The output will be Here the code inside the main() executes first, and then the deferred function calls are executed in the reverse order, i.e. 4, 3,2,1.

Pointers

Before explaining pointers let’s will first discuss ‘&’ operator. The ‘&’ operator is used to get the address of a variable. It means ‘&a’ will print the memory address of variable a. In this Golang tutorial, we will execute the below program to display the value of a variable and the address of that variable The result will be A pointer variable stores the memory address of another variable. You can define a pointer using the syntax The asterisk(*) represents the variable is a pointer. You will understand more by executing the below program The output will be

Structures

A Structure is a user defined datatype which itself contains one more element of the same or different type. Using a structure is a 2 step process. First, create(declare) a structure type Second, create variables of that type to store values. Structures are mainly used when you want to store related data together. Consider a piece of employee information which has name, age, and address. You can handle this in 2 ways Create 3 arrays – one array stores the names of employees, one stores age and the third one stores age. Declare a structure type with 3 fields- name, address, and age. Create an array of that structure type where each element is a structure object having name, address, and age. The first approach is not efficient. In these kinds of scenarios, structures are more convenient. The syntax for declaring a structure is An example of a structure declaration is Here a new user defined type named emp is created. Now, you can create variables of the type emp using the syntax An example is You can set values for the empdata1 as You can also create a structure variable and assign values by Here, you need to maintain the order of elements. Raj will be mapped to name, next element to address and the last one to age. Execute the code below Output

Methods(not functions)

A method is a function with a receiver argument. Architecturally, it’s between the func keyword and method name. The syntax of a method is Let’s convert the above example program to use methods instead of function. Go is not an object oriented language and it doesn’t have the concept of class. Methods give a feel of what you do in object oriented programs where the functions of a class are invoked using the syntax objectname.functionname()

Concurrency

Go supports concurrent execution of tasks. It means Go can execute multiple tasks simultaneously. It is different from the concept of parallelism. In parallelism, a task is split into small subtasks and are executed in parallel. But in concurrency, multiple tasks are being executed simultaneously. Concurrency is achieved in Go using Goroutines and Channels.

Goroutines

A goroutine is a function which can run concurrently with other functions. Usually when a function is invoked the control gets transferred into the called function, and once its completed execution control returns to the calling function. The calling function then continues its execution. The calling function waits for the invoked function to complete the execution before it proceeds with the rest of the statements. But in the case of goroutine, the calling function will not wait for the execution of the invoked function to complete. It will continue to execute with the next statements. You can have multiple goroutines in a program. Also, the main program will exit once it completes executing its statements and it will not wait for completion of the goroutines invoked. Goroutine is invoked using keyword go followed by a function call. Example You will understand goroutines with the below Golang examples. Execute the below program The output will be Here the main program completed execution even before the goroutine started. The display() is a goroutine which is invoked using the syntax In the above code, the main() doesn’t wait for the display() to complete, and the main() completed its execution before the display() executed its code. So the print statement inside display() didn’t get printed. Now we modify the program to print the statements from display() as well. We add a time delay of 2 sec in the for loop of main() and a 1 sec delay in the for loop of the display(). The output will be somewhat similar to Here You can see both loops are being executed in an overlapping fashion because of the concurrent execution.

Channels

Channels are a way for functions to communicate with each other. It can be thought as a medium to where one routine places data and is accessed by another routine in Golang server. A channel can be declared with the syntax Example: You can send data to a channel using the syntax Example You can receive data from a channel using the syntax Example In the above Go language examples of goroutine, you have seen the main program doesn’t wait for the goroutine. But that is not the case when channels are involved. Suppose if a goroutine pushes data to channel, the main() will wait on the statement receiving channel data until it gets the data. You will see this in below Go language examples. First, write a normal goroutine and see the behaviour. Then modify the program to use channels and see the behaviour. Execute the below program The output will be The main() finished the execution and did exit before the goroutine executes. So the print inside the display() didn’t get executed. Now modify the above program to use channels and see the behaviour. The output will be Here what happens is the main() on reaching x := <-ch will wait for data on channel ch. The display() has a wait of 5 seconds and then push data to the channel ch. The main() on receiving the data from the channel gets unblocked and continues its execution. The sender who pushes data to channel can inform the receivers that no more data will be added to the channel by closing the channel. This is mainly used when you use a loop to push data to a channel. A channel can be closed using And at the receiver end, it is possible to check whether the channel is closed using an additional variable while fetching data from channel using If the status is True it means you received data from the channel. If false, it means you are trying to read from a closed channel You can also use channels for communication between goroutines. Need to use 2 goroutines – one pushes data to the channel and other receives the data from the channel. See the below program Here there are 2 subroutines one pushes data to the channel and other prints data to the channel. The function add_to_channel adds the numbers from 0 to 9 and closes the channel. Simultaneously the function fetch_from_channel waits at x, flag := <- ch and once the data become available, it prints the data. It exits once the flag is false which means the channel is closed. The wait in the main() is given to prevent the exiting of main() until the goroutines finish the execution. Execute the code and see the output as

Select

Select can be viewed as a switch statement which works on channels. Here the case statements will be a channel operation. Usually, each case statements will be read attempt from the channel. When any of the cases is ready(the channel is read), then the statement associated with that case is executed. If multiple cases are ready, it will choose a random one. You can have a default case which is executed if none of the cases is ready. Let’s see the below code Executing the above program will give the output: Here the select statement waits for data to be available in any of the channels. The data2() adds data to the channel after a sleep of 2 seconds which will cause the second case to execute. Add a default case to the select in the same program and see the output. Here, on reaching select block, if no case is having data ready on the channel, it will execute the default block without waiting for data to be available on any channel. This program will give the output: This is because when the select block reached, no channel had data for reading. So, the default case is executed.

Mutex

Mutex is the short form for mutual exclusion. Mutex is used when you don’t want to allow a resource to be accessed by multiple subroutines at the same time. Mutex has 2 methods – Lock and Unlock. Mutex is contained in sync package. So, you have to import the sync package. The statements which have to be mutually exclusively executed can be placed inside mutex.Lock() and mutex.Unlock(). Let’s learn mutex with an example which is counting the number of times a loop is executed. In this program we expect routine to run loop 10 times and the count is stored in sum. You call this routine 3 times so the total count should be 30. The count is stored in a global variable count. First, You run the program without mutex See the result The result could be different when you execute it but the final result won’t be 30. Here what happens is 3 goroutines are trying to increase the loop count stored in the variable count. Suppose at a moment count is 5 and goroutine1 is going to increment the count to 6. The main steps include Copy count to temp Increment temp Store temp back to count Suppose soon after performing step 3 by goroutine1; another goroutine might have an old value say 3 does the above steps and store 4 back, which is wrong. This can be prevented by using mutex which causes other routines to wait when one routine is already using the variable. Now You will run the program with mutex. Here the above mentioned 3 steps are executed in a mutex. Now the output will be Here we get the expected result as final output. Because the statements reading, incrementing and writing back of count is executed in a mutex.

Error handling

Errors are abnormal conditions like closing a file which is not opened, open a file which doesn’t exist, etc. Functions usually return errors as the last return value. The below example explains more about the error. The output will be: Here we tried to open a non-existing file, and it returned the error to er variable. If the file is valid, then the error will be null

Custom errors

Using this feature, you can create custom errors. This is done by using New() of error package. We will rewrite the above program to make use of custom errors. Run the below program The output will be: Here the area() returns the area of a square. If the input is less than 1 then area() returns an error message.

Reading files

Files are used to store data. Go allows us to read data from the files First create a file, data.txt, in your present directory with the below content. Now run the below program to see it prints the contents of the entire file as output Here the data, err := ioutil.ReadFile(“data.txt”) reads the data and returns a byte sequence. While printing it is converted to string format.

Writing files

You will see this with a program Here a file is created, test.txt. If the file already exists then the contents of the file are truncated. Writeline() is used to write the contents to the file. After that, You closed the file using Close().

Cheat Sheet

In this Go tutorial, we covered,