Go Programming Language Tutorial: Learn Golang with Example

What is Go?

Go (also known as Golang) is an open source programming language developed by Google. It is a statically-typed compiled language. Go supports concurrent programming, i.e. it allows running multiple processes simultaneously. This is achieved using channels, goroutines, etc. Go has garbage collection which itself does the memory management and allows the deferred execution of functions.

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

go version

This will display the version of go installed

Your First Go program

Create a folder called studyGo. You will create our go programs inside this folder. Go files are created with the extension .go . You can run Go programs using the syntax

go run <filename>

Create a file called first.go and add the below code into it and save

package main
import ("fmt")

func main() {
	fmt.Println("Hello World! This is my first Go program\n")
}

Navigate to this folder in your terminal. Run the program using the command

go run first.go

You can see the output printing

Hello World! This is my first Go program

Now let’s discuss the above program.

package main - Every go 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 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

go run <filename>

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.

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

var <variable_name> <type>

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

    var <variable_name> <type> = <value>

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

    var <variable_name> = <value>

Also, You can declare multiple variables with the syntax

    var <variable_name1>, <variable_name2>  = <value1>, <value2>

The program below has some examples of variable declarations

 
package main
import "fmt"

func main() {
    //declaring a integer variable x
    var x int
    x=3 //assigning x the value 3 
    fmt.Println("x:", x) //prints 3
    
    //declaring a integer variable y with value 20 in a single statement and prints it
    var y int=20
    fmt.Println("y:", y)
    
    //declaring a variable z with value 50 and prints it
    //Here type int is not explicitly mentioned 
    var z=50
    fmt.Println("z:", z)
    
    //Multiple variables are assigned in single line- i with an integer and j with a string
    var i, j = 100,"hello"
    fmt.Println("i and j:", i,j)
}

The output will be

x: 3
y: 20
z: 50
i and j: 100 hello
<variable_name> := <value>

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

package main
import ("fmt")

func main() {
	a := 20
	fmt.Println(a)

	//gives error since a is already declared
	a := 30
	fmt.Println(a)
}

Execute go run assign.go to see the result as

./assign.go:7:4: no new variables on left side of :=

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 is declared by using the keyword “const”

Create a file called constant.go and with the following code

package main
import ("fmt")

func main() {
	const b =10
	fmt.Println(b)
	b = 30
	fmt.Println(b)
}

Execute go run constant.go to see the result as

.constant.go:7:4: cannot assign to b

Loops

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 supports only for loop.

The syntax of a for loop is

for initialisation_expression; evaluation_expression; iteration_expression{
   // one or more statement
}

The initialisation_expression is executed first(and only once).

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 for loop printing numbers from 1 to 5

package main
import "fmt"

func main() {  
var i int
for i = 1; i <= 5; i++ {
fmt.Println(i)
    }
}

Output is

1
2
3
4
5

Refer: guru99.com