Google Go Tutorial

What is Google Go?

Google Go is an open-source programming language designed at Google by Robert Griesmer, Rob Pike, and Ken Thompson. Go is syntactically similar to C language; in addition to memory safety, garbage collection, structural typing and CSP style concurrency. It has a rich standard library. It initially developed in the year 2007 and launched in November 2009. It is updated recently on April 11, 2019. Google Go is also termed as Golang. Golang is the implementation of assembly language (GC) and C++` (gccgo). Prerequisites For Go programming language, one should be familiar with C programming. If you are good at C, then it would be easy for you to understand the concept of Go programming. I have tried to make this tutorial easy and start it from scratch level.

Features of Go programming

Some of its essential features are as follows-
  • Fast compilation
  • Inbuilt concurrency support
  • It supports interfaces and type embedding
  • It is modern fast and powerful.
Some of its features are excluded intentionally to keep it concise and straightforward. Some of the Go’s  excluded Features are-
  • Type inheritance support
  • The method or operator overloading
  • Pointer arithmetic
  • Assertions support
  • Generic programming support

Structure of Go programs

The basic structure of Go programs contains the following parts-
  • Declaration packages
  • Import packages
  • Variables
  • Statement and Expression
  • Function
  • Comments

A Beginners Guide to Go installation Step by Step

Go programming can be installed on a different operating system like Windows, Linux, Mac, etc. For installing Go language, go to its official website golang.org. Select desired package for Operating system like for windows 7, select the setup available for window7, and follow the installation process. Setting environment variable (for windows) You can find the setting for environmental variables on the “advanced” tab of the “system” control panel. Check Go version- You can check the version of the Go language by using go version command. First Go program We can write Go code on any basic editor in any desired directory and save it with extension .go
package main

import ("fmt")

func main() {

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

}
Save it with the extension .go. I saved it as First.go Execution- open command prompt and type command- go run First.go Output-
Hello world! This is my first Go program
Have a look at the following image.  Go Hello world Go package, import, and visibility Packages- Our program for easy maintenance categorizes packages. Every file of Go program belongs to some packages. Each Go program must have "main" package. Package’s name should be written in lowercase letters. If a package is changed and recompiled, all the client’s programs belong to that package must be recompiled too. Import- Import is used to import any package from the library. A Go program is linked to the different package through the import keyword. We can import multiple packages by a single statement, Like-
import “fmt”
import “os”
or we can write as       import “fmt”;import”os”
We can use one more way-
import(

“fmt”

“os”)

Or import(“fmt;”os”
Visibility- The identifier can be a variable, function, type or struct field or constant. The identifier can be declared as in the lower case or upper case. If the identifier declared in lowercase, then it will be visible inside the package. If declared in uppercase, then it will be visible inside or outside the package which is called export. A dot (.) operator is used to access the identifier: Eg. pack.Date, Here pack, is the package name and date is the identifier.

Google Go Data types

Data types represent the type of value stored in a variable, type of the value a function returns, etc. There are three basic data types in Go-
  • Numeric type
  • String type
  • Boolean type
Numeric type- It represents various numeric values like integer, floating point, and complex values. Some of its types are-
  • In8 (8bit signed integer)
  • Int16 (16bit signed integer)
  • Int32 (32bit signed integer)
  • Int64 (64 bit signed integer)
  • Uint8 (8bit unsigned integer)
  • Uint16 (16bit unsigned integer)
  • Uint32 (32bit unsigned integer)
  • Uint64 (64bit unsigned integer)
  • Float32 (32bit floating point numbers)
  • Float64 (64bit floating point numbers)
  • Complex64 (Has float 32 real and imaginary part)
  • Complex128 (Has float 32 real and imaginary part)
String- A String represents a sequence of characters (bytes). Various operations can be performed in a string like concatenation, extracting substring, etc. Boolean types- It represents only two values either true or false. Variables- Variables refer to a memory location for storing some value. The type parameter represents the value type that can be stored in the memory. Syntax-
Var <variable_name> <type>
Once a variable is declared then you can assign the variable type value. You can also give an initial value at the time of declaration of the variable.
Var <variable_name> <type> = <value>
Multiple variables can also be declared in a single statement-
Var <variable_name1>, <variable_name2> = <value1>, <value2>
A Go program for understanding variables-
package main

import “fmt”

func main() {

var a int      //variable declaration

  a=3 //assigning value 3 in a

    fmt.Println("a:", a) //prints 3

 //declaring a integer variable b with value 20

    var b int

b=20

    fmt.Println("b:", b)

   

    //declaring a variable c with value 50

    var c=50

    fmt.Println("c:", c)

   

    //Multiple variables are assigned in single line- p with an integer and q with a string

    var p, q = 100,"hello"

    fmt.Println("p and q:", p,q)

}
Output-
a: 3

b: 20

c: 50

p and q: 100 hello
Constant Variables- Constant Variable is declared by using the keyword "const".  Value of constant variables cannot be changed if once assigned. Example-
package main

import ("fmt")

func main() {

            const x =50

            fmt.Println(x)

            x = 20

            fmt.Println(x)

}
Output-
.constant.go:7:4: cannot assign to b
Loops in Go- Loops are used to execute a block of code repeatedly according to the given condition. Most programming languages support three types of loop, for, while and do while. Note: Go supports only for loops. Syntax-
for initialization_expression; evaluation_expression; iteration_expression{s

// statements

}
The initialization_expression is executed first then the evaluation_expression is evaluated. If it's true, then block code is executed. The itereation_expression id is executed, and the loop starts again. This process will continue until the evaluation_expression becomes false. Program for loop-
package main

import "fmt"



func main() { 

var i int

for i = 0; i <= 7; i++ {

fmt.Println(i)

    }

}
Output-
0

1

2

3

4

5

6

7
Conditional statement- The if-else statement- It is a conditional statement. Syntax
if condition

{ // statement1

}

else

{// statement2

}
Go program for checking the given number is positive or negative-
package main

import "fmt"



func main() { 

    int i;

    if i< 0 {

        //Executes if i< 0

        fmt.Println("i is negative")

    }

else{

fmt.println(“I is positive)

}
The Switch statement- The switch is also a conditional statement. Switch statement compares the conditions and evaluates a result.  Once a match is found, the statement associated with that case is executed. We can also add a default case to switch which will be executed if no other matches are found. Syntax-
switch expression {

    case 1:

        statement_1

    case 2:

        statement_2

    case n:

        statement_n

    default:

        statement_default

    }
Program for switch case-
package main

import "fmt"

func main() { 

    x,y := 10,5

    switch x+y {

    case 1:

        fmt.Println("Sum is 15")

    case 2:

        fmt.Println("Sum is 20")

    case 3:

        fmt.Println("Sum is 30")

    default:

        fmt.Println("Printing default")

    }

}
Output-    
sum is 15
The Goto statement- The Goto is a jump statement. It is used to transfer the control to other parts of program. Every Goto statement has a label, we use that label to transfer the control of the program. Example-
Package main

Import (“fmt”)

Func main() {

Var input int

Loop: 

   fmt.Print("You  are a child ") 

   fmt.Print("Enter  age ") 

   fmt.Scanln(&input) 

   if (input <= 18) { 

      goto Loop 

   } else { 

      fmt.Print("you are a man") 

   } 

}
Output-
You are a child

Enter your age 12

You are a child

Enter your age 19

You are a man
The break statement in Go- The break statement can be used in for loop for the counter, condition etc. It can also be used in the switch statement. A break statement is used to break out of the innermost statement in which it occurs. Syntax-
break;
Example of break statement-
package main 

import "fmt" 

func main() { 

   var  x int = 1 

   for x< 10{ 

      fmt.Print("Value of x is ",x,"\n") 

      x++; 

      if x > 5{ 

         /* Terminate the loop using break statement */  

         break; 

      } 

   } 

}
Output-
Value of x is 1

Value of x is 2

Value of x is 3

Value of x is 4

Value of x is 5
Arrays – An Array is a collection of elements which have the same types of data. The Array represents a fixed size and named a sequence of elements. An array cannot have an element with two different data type. We can’t change the size of an array if once defined.
Syntax- var arrayname [size] type
Each array element can be assigned value as-
arrayname [index]= value
Index of array starts from size 0 to 1 We can assign the values to array at the declaration time-
arrayname:=[size] type { value_0,value_1,value_2,…….,value_n}
Example for Go array-
package main

import "fmt"

func main() { 

    var numbers [3] string // string declaration of array size 3

    numbers[0] = "One"

    numbers[1] = "Two"

    numbers[2] = "Three"

    fmt.Println(numbers[1]) //prints Two

    fmt.Println(len(numbers)) //prints 3

    fmt.Println(numbers) // prints [One Two Three]

    directions := [...] int {1,2,3,4,5} // creating an integer array and the size of the array is defined by the number of elements

    fmt.Println(directions) //prints [1 2 3 4 5]

    fmt.Println(len(directions)) //prints 5

}
Output-
Two

3

[One two three]

[1 2 3 4 5]

5
Slice in Go- A slice is a segment of an array, or a partial view of an underlying array to which it points. You can access the slice name and index number just as in an array. We can change the size of the slice, but we cannot change the size of an array.  Contents of the slice are actually the pointers of the array. If we change the elements in slice then it also affects the contents of the array. Syntax-
Var slice_name [] type= array_name [start: end]
This will create a slice name from an array with elements at the index start to end -1.