Learn Go Language Step by Step Fast and Simple Way in 2020

6
26
learn Go Language
learn Go Language
Spread the love

Google launched a simple yet powerful opensource language called Go popularly known as Golang. Want to learn Go Language? Want to know how Google and open source community is helping the developers in designing the software. Here is a post that talks about the detail of Go language.

The topics on GO.

I am going to covert are as follows:

Basic Golang

  • Benefits of Golang
  • How to install GO on windows?
  • Installation in UBUNTU:
  • First Program in GO
  • Executing a Go Program
  • Tokens in Go
  • Line Separator
  • Identifiers
  • Some reserved keywords in GO.
  • Data Types in GO
  • Floating Point Numbers
  • String
  • Booleans
  • Decision Statements in GO
  • If Statement
  • Go if-else
  • Nested if/else in GO
  • Go switch
  • Looping in Golang
  • For loop
  • Nested for loop in GO
  • Infinite for loop in GO
  • Go for range loop
  • Go Goto Statement
  • Go Break Statement
  • Go Continue Statement
  • Go Comments
  • Go Multi Line Comment
  • Go Type Casting

Advanced Golang

  • Go Functions
  • Function Prototypes
  • How to return multiple Answers from a function in GO?
  • Recursive Function in GO
  • Closure in GO
  • Go Array
  • Go Multi-Dimensional Array
  • Go Slice
  • Slice Literal
  • Slice Length and Capacity
  • Structures in GO
  • Interfaces in GO
  • Go Pointers
  • Practice Questions of Golang

Let’s touch on a few important goals of these tutorials before we get started.  For instance, books will skip programming style sections, common pitfalls, debugging, good /bad programming practices and debugging. This tutorial covers best programming practice exercises and programs for you to learn and understand easily.

  • This Blog Tutorial consists of a lot of daily life example programs for the understanding of concepts, which helps learners to understand in an effective and better way.
  • Provide practice programs at the end of tutorial documents.

Introduction on GO

Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. Go is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency.

Go language is a programming language. It is a language with a static syntax that is also similar to C. It offers waste collection, security type, dynamics, a lot of advanced embedded types, like variable-length arrays and keymaps. It also offers a rich library. The Go programming language was launched in November 2009 and is used in some manufacturing systems by Google.
First Appeared: November 10, 2009;

Designed byRobert Griesemer, Rob Pike, Ken Thompson. link here

Benefits of Go language

Go is designed specifically as a systems programming language for large, distributed systems and highly-scalable network servers. In that vein, it replaces C++ and Java in Google’s software stack.

  • Go is modern, fast and comes with a powerful standard library.
  • Go has built-in concurrency.
  • Go uses interfaces as the building blocks of code reusability.

This is the first point to learn Go Language.

Go Language is a Compiled language

Go is a compiled language. Compiled languages are known for their speed, as they’re converted directly into machine-level code that can be read directly by the computer instead of being interpreted every time the application is run, like JavaScript on a web page. So, when you’re done writing source code, it’s run through a compiler which converts the source code into an executable file that can be distributed to run the program on another machine.

Go compiler
In addition to its quickness as a compiled language, the Go compiler offers additional benefits like being able to check for errors, easier deployment and the ability to optimize your code for efficiency.
Error checking
The Go compiler’s error checking is able to detect variables that went unused, missing packages or imports necessary to run and mistyped or invalid operations.

The compiler finds these errors during the build process of your program. Consequently, Go is able to give you a heads up about what works and what doesn’t before you even run your program—saving you time during development without having to search for bugs.
Cross-compiling
Another unique feature of Go is the ability to cross-compile your application to run on a different machine than the one used for development. The Go compiler allows you to generate executable binaries for different operating systems with simple commands. Instead of requiring Go to be installed on foreign machines, you can easily cross-compile your original source code to run on multiple machines. This makes deploying Go applications to production servers or local machines a breeze—all it requires is moving the final executable file.

Additional benefits of Go

We must know the below attributes of Go to learn Go Language.

Garbage collection
Garbage collection, or automatic memory management, is a key feature of the Go language. Go excels in giving a lot of control over memory allocation and has dramatically reduced latency in the most recent versions of the garbage collector, with average latencies below 1ms. Go’s garbage collector achieves this by running concurrently with the program and by using a tricolour mark-and-sweep algorithm.
Scalability
Because Go was built by Google, it was designed with scalability in mind. As applications grow, they need to handle many smaller sub-tasks at the same time, like delivering HTML pages to individual web browsers. Running simultaneous tasks within an application is called concurrency. Go has many built-in features designed to handle concurrency, most notably goroutines and channels.

Goroutines are functions capable of running concurrently with other functions. Channels allow different goroutines to communicate with each other to determine how best to complete a task.
Simplicity
Finally, Go excels in being simple and easy to understand. With a very small language specs document, Go strives to be easy to both read and write. The official Go website also includes a tutorial to get started with the language by typing and practising code in the browser.

How to install GO on windows?

This is the first step to learn Go Language.

Stepts

  • Choose the required archive file for Windows installation.
  • Download zip file and extract it into the directory (Like c:\Go).
  • If you have chosen a different directory other than c:\Go, you must set the GOROOT environment variable to your chosen path.
  • Add the bin subdirectory of your Go root (for example, c:\Go\bin) to your PATH environment variable.

Installation in UBUNTU:

This is the second step to learn Go Language.

Step 1: Run the command sudo apt-get install Golang

Step 2

Step 3

Step 4

First Program in GO

There is nothing satisfactory to write hello world to learn Go Language.

import "fmt"
func main() {
/* This is my first sample program. */
fmt.Println("Hello, World ")
}

Output:
Hello, World

The below attrites of the code just to remember to learn Go Language.

  • The first line of the main package defines the name of the package that this program should be. It is mandatory, as Go programs are running in packages. The main package is where the program starts. Every package is accompanied by a path and name.
  • The following line import command “fmt” tells the Go compiler to include the files in package fmt.
  • The main function where the program starts is the next line func main).
  • The compiler ignores the next line / *…* and adds comments to this software. Comments are also shown using / like Java or C++.
  • The next line is the fmt. Println(…) function, which shows the message’ Hello, World!’ on the screen. Here fmt package exported Println method to show the message on the screen.
  • Notice the Println Method’s capital P. In Go language, if it begins with the main letter, the name is exported. Exported means that an importer of the respective package has access to the function or variable/constant.

Executing a Go Program

Note: This is the method for Execution and keeps in mind this method is followed in all tutorial. learn Go Language is not completed before we know the execution.

Open the compiler which we installed previously, then write code into it and then compile the code from compile button.

Tokens in Go

The token is an important concept to learn Go Language. There are various tokens in a Go program. A token is one keyword, one identifier, one constant, one literal string, or one symbol. The next Go statement includes six tokens, for example
This is an induvial token in GO.


Println
(
"Hello, World!"
)

Line Separator

The line separator key is a declaration terminator in a Go program. In other words, the separators such as;” “in C do not need individual statements. The Go compiler internally sets “;” to indicate the end of a logical entity as a statement terminator.


fmt.Println("Hello, World!")
fmt.Println("I am in Go Programming World!")

Identifiers

A Go-ID is a name for a variable, function or any other user-defined item. A letter A to Z or z, or an under script begins with an identifier, followed by zero or more letters, emphasis, and digits (0 to 9).

Some reserved keywords in GO.

Data Types in GO

There are many data types some of them with example program is as below: Datatypes are also very important concept to  learn Go Language


var a int
var b bool
var str string
Example:

package main
import"fmt"
func main()
{
var i int
var f float64
var b bool
var s string
fmt.Printf("%T %T %T %T\n",i,f,b,s) // Prints type of the variable
fmt.Printf("%v   %v      %v  %q     \n", i, f, b, s) //prints initial value of the variable
}

Output:
int float64 bool string
0 0 false “”

Floating Point Numbers

Numbers containing a decimal component (true numbers) are floating-point numbers. Their actual computer representation is rather complex and not necessarily necessary in order to learn to use them (1.234, 123.4, 0.00001234 and 12340000). Therefore, we just have to remember:

Example:

Numbers containing a decimal component (true numbers) are floating-point numbers. Their actual computer representation is rather complex and not necessarily necessary in order to learn to use them (1.234, 123.4, 0.00001234 and 12340000). Therefore, we just have to remember:

Output:

$ go run main.go

1 + 1 = 2
String in Go language

As we have seen in the second chapter, a character sequence is used for the representation of the text in a defined length. Go strings consist of single bytes, usually one for each character. String literal may be created using double quotes “Hello World” or backticks ‘Hello World.’ (Characters from other languages such as Chinese are represented by more than one byte.). The difference is that double quoted strings do not include newlines and allow special escape sequences. For instance: a newline replaces \n and a tab character replaces \t.

Example:


package main
import "fmt"
func main() {
fmt.Println(len("Hello World India"))
fmt.Println("Hello World"[1])
fmt.Println("Hello " + "World India ")
}

Booleans

A Boolean value is an a special 1-bit entire type (or on and off) which is used to represent true and false. Boolean values are used by three logical operators:

Example:


func main() {
fmt.Println(true && true)
fmt.Println(true && false)
fmt.Println(true || true)
fmt.Println(true || false)
fmt.Println(!true)
}

Output:
$ go run main.go
true
false
true
true
false

Decision Statements in GO

If Statement

Type in anything that you want. Then click Quill It on the right to paraphrase your input.
Syntax:


if(boo_expression100)
{
/* statement(s) got executed only if the expression results in true */
}

Example:

package main
import"fmt"
func main() {
/* local variable definition  is here*/
var a int = 10
/* check the boolean condition using if statement */
if( a % 2==0 ) {      /* if condition is true then print the following
*/ fmt.Printf("a is even number" )
}
}

Output:
a is even number

Go if-else

The if-else is used for testing. If the condition is true, block otherwise executed block
Syntax:


if(boolean_expression)
{
/* statement(s) got executed only if the expression results in true */
}
else
{
/* statement(s) got executed only if the expression results in false */
}

Example:


package main
import "fmt"
func main()
{
/* local variable definition */
var a int = 10;
/* check the boolean condition */
if( a%2 == 0 ) {
/* if condition is true then print the following */
fmt.Printf("a is even\n");
} 
else {
/* if condition is false then print the following */
fmt.Printf("a is odd\n");
}
fmt.Printf("value of a is : %d\n", a);
}

Output:
a is even
value of a is : 10
This example shows how to take input from user


func main() {
fmt.Print("Enter number: ")
var input int
fmt.Scanln(&input)
fmt.Print(input)
/* check the boolean condition */
if( input % 2==0 )
{
/* if condition is true then print the following */
fmt.Printf(" is even\n" );
} 
else {
/* if condition is false then print the following */
fmt.Printf(" is odd number\n" );
}
}

Output:
Enter number: 10
10 is even

Nested if/else in GO

The Go if otherwise if chain is used to perform multiple conditions for one statement. We can have N if-else declaration numbers. It’s no boundary.

If-else statement even if you have one statement in it, the curly{} braces are obligatory. After the curly brace closing, the other if and other words should be on the same line.

Example:


package main
import "fmt"
func main() {
fmt.Print("Enter text: ")
var input int
fmt.Scanln(&input)
if (input < 0 || input > 100) {
fmt.Print("Please enter valid no")
}
else if (input >= 0 && input < 50  ) {
fmt.Print(" Fail")
} 
else if (input >= 50 && input < 60) {
fmt.Print(" D Grade")
} 
else if (input >= 60 && input < 70  ) {
fmt.Print(" C Grade")
} 
else if (input >= 70 && input < 80) {
fmt.Print(" B Grade")
} 
else if (input >= 80 && input < 90  ) {
fmt.Print(" A Grade")
} 
else if (input >= 90 && input <= 100) {
fmt.Print(" A+ Grade")
}
}

Output:
Enter text: 84
A Grade

Example:


    if( boolean_expression 1) {
        /* statement(s) got executed only if the expression 1 results in true */
       if(boolean_expression 2) {
        /* statement(s) got executed only if the expression 2 results in true */
       }
    }
    package main
    import "fmt"
    func main() {
       /* local variable definition */
       var x int = 10
       var y int = 20
       /* check the boolean condition */
       if( x >=10 ) {
          /* if condition is true then check the following */
          if( y >= 10 )  {
             /* if condition is true then print the following */
             fmt.Printf("Inside nested If Statement \n" );
          }
       }
       fmt.Printf("Value of x is : %d\n", x );
       fmt.Printf("Value of y is : %d\n", y );
    }

Output:
Inside nested If Statement
Value of x is : 10
Value of y is : 20

Go switch

A switch statement allows equality testing of a variable against a list of values. Each value is called a case, and the variable to be switched on for each case is checked.
Syntax:

    switch  var1 {
    case val1:
    .....
    case val2
    .....
    default:
    .....
    }

The expression used in a switch statement must be of an integral or enumerated type, or of a class type where the class has a single conversion function to an integral or enumerated type.

Within a switch you can get any number of case statements. Each case is followed by the value and a colon to be compared with.

For a case, the constant-expression must be the same data type as the switch variable, and it must be a constant or a literal one.

When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

When a break statement is reached, the switch will terminate, and the control flow will jump to the next line after the switch statement.

Not every case needs a break in it. If no break appears, then it will raise a compile-time error.

A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true.

When a break statement is reached, the switch will terminate, and the control flow will jump to the next line after the switch statement.

Not every case needs a break in it. If no break appears, then a compile-time error will be raised.

An optional default case may have a switch statement, which must appear at the end of the switch. When none of the cases is true, the default case may be used to perform a task.

Example:


package main
import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"strconv"
	"strings"
)
func parseArgs(c []string) (float64, float64, error) {
	num1, err := strconv.ParseFloat(c[0], 64)
	if err != nil {
		return 0.0, 0.0, err
	}
	num2, err := strconv.ParseFloat(c[2], 64)
	if err != nil {
		return 0.0, 0.0, err
	}
	return num1, num2, nil
}
func processStack(e []string) (float64, error) {
	result := 0.0
	for _, v := range e {
		c := strings.Split(v, " ")
		if len(c)-1 < 2 { return 0.0, errors.New("error: some arguments are not supplied") } num1, num2, err := parseArgs(c) if err != nil { return 0.0, err } switch c[1] { case "*": result = num1 * num2 case "/": if num2 == 0.0 { return 0.0, errors.New("error: you tried to divide by zero.") } result = num1 / num2 case "+": result = num1 + num2 case "-": result = num1 - num2 } } return result, nil } func main() { expressions := make([]string, 1) for { scanner := bufio.NewScanner(os.Stdin) fmt.Print("gocalc>")
		for scanner.Scan() {
			expressions = append(expressions, scanner.Text())
			res, err := processStack(expressions)
			if err != nil {
				fmt.Println(err)
			} else {
				fmt.Println(res)
			}
			fmt.Print("gocalc>")
		}
	}
}

Example:

1.	import "fmt"  
	func main() {  
	   k := 30  
	   switch k {  
	   case 10:  
	      fmt.Println("was <= 10"); fallthrough;  
	   case 20:  
	      fmt.Println("was <= 20"); fallthrough;  
	   case 30:  
	      fmt.Println("was <= 30"); fallthrough;  
	   case 40:  
	      fmt.Println("was <= 40"); fallthrough;  
	   case 50:  
	      fmt.Println("was <= 50"); fallthrough;  
	   case 60:  
	      fmt.Println("was <= 60"); fallthrough;  
	   default:  
	      fmt.Println("default case or end case")  
	   }  
}

Output:

was <= 30
was <= 40
was <= 50
was <= 60
default case or end case

Looping in Golang

There may be a situation where several times you need to execute a block of code. The statements are generally executed sequentially: the first statement in a function is executed first, then the second, and so on.

Programming languages provide different control structures which enable more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and in most programming, languages is the general statement from a loop statement.

Use the syntax of the example below instead of While loop

A while loop statement in GO repeatedly executes a target statement as long as a given condition is true. But it is different from C++. It can be calculated manually.

Here, a statement(s) can be a single statement or a statement block. The condition can be any expression, and true is any value other than zero. The iterates the loop while the condition is true.

When the condition becomes false the control of the program passes immediately after the loop to the line.


package main
import "fmt"
func main() {
	sum := 1
	for sum < 1000 {
		sum += sum
	}
	fmt.Println(sum)
}

For loop in Golang

The for keyword indicates a loop in GO. The for loop executes a block of statements repeatedly until the specified condition returns false.
The for loop contains three parts according to the above syntax: initialization, conditional expression, and steps, which are separated by a semicolon.

Initialization variable: here declare & initialize a variable to be used in conditional expression and part of steps.
Condition: Boolean expression is the condition which will return either true or false.

Steps: The incremental or decremental part defines steps.
Example:


	package main  
	import "fmt"  
	func main() {  
	   for a := 0; a < 11; a++ {  
	      fmt.Print(a,"\n")  
	   }  
}  

Output:
0
1
2
3
4
5
6
7
8
9
10

Nested for loop in GO

Loop within a loop is called nested loop.

package main  
	import "fmt"  
	func main() {  
	   for a := 0; a < 3; a++ { for b := 3;b > 0; b-- {  
	         fmt.Print(a," ",b,"\n")  
	      }  
	   }  
}

Output:

0 3
0 2
0 1
1 3
1 2
1 1
2 3
2 2
2 1

Infinite for loop in GO


	package main  
	import "fmt"  
	func main() {  
	   for true  { fmt.Printf("Executes infinitely	.\n");  
	   }  
} 

Output:
Executes infinitely

Go for range loop

In many contexts, the range structure is useful. It is possible to cross all items in a collection. In other languages it’s similar to foreach. But at every iteration in the range construction we still have the index.


	import "fmt"  
	func main() {  
	   nums := []int{2, 3, 4}  
	   sum := 0  
	   for _, value := range nums {// "_ " is to ignore the index  
	      sum += value  
	   }  
	   fmt.Println("sum:", sum)  
	   for i, num := range nums {  
	      if num == 3 {  
                fmt.Println("index:", I)  
	      }  
	   }  
	   kvs := map[string]string{"1":"mango","2":"applewao","3":"banana12"}  
	   for k, v := range kvs {  
	      fmt.Printf("%s -> %s\n", k, v)  
	   }      
	   for k := range kvs {  
	      fmt.Println("key:", k)  
	   }  
	   for i, c := range "Hi" {  
	      fmt.Println(i, c)  
	   }  
	} 

Output:

sum: 60
1 -> mango
2 -> applewao
3 -> banana12
key: 1
key: 2
key: 3
0 72
1 105

Go Goto Statement

The Go Goto declaration is a jump declaration that transfers the control to other parts of the program. There must be a label in Goto declaration. To transfer program control, we use the label.

Example:


	package main  
	import (  
	   "fmt"  
	)  
	func main() {  
	   var input int  
	Loop:  
	   fmt.Print("You are not eligible to vote ")  
	   fmt.Print("Enter your age ")  
	   fmt.Scanln(&input)  
	   if (input <= 17) {  
	      goto Loop  
	   } else {  
	      fmt.Print("You can vote ")  
	   }  
}

Output:

You are not eligible to vote
Enter your age 15
You are not eligible to vote
Enter your age 18
You can vote

Go Break Statement

To break from the innermost structure, a break statement is employed. The for-loop (counter, condition, etc) can be used as well as in a shutter. After the completion of this structure is continued.

Example:

package main  
	import "fmt"  
	func main() {  
	   var  a int = 1  
	   for a < 10{ fmt.Print("Value of a is ",a,"\n") a++; if a > 5{  
         /* terminate the loop using break statement */  
	         break;  
	      }  
	   }  
      }

Output:

Value of a is 1
Value of a is 2
Value of a is 3
Value of a is 4
Value of a is 5

Example:

package main  
  import "fmt"  
  func main() {  
     var a int  
     var b int  
     for a = 1; a <= 3; a++ {  
        for b = 1; b <= 3; b++ {  
           if (a == 2 && b == 2) {  
              break;  
          }  
          fmt.Print(a, " ", b, "\n")  
      }  
    }  
 }  

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Go Continue Statement

The continue is used to skip the remaining part of the loop, and then continues with the next iteration of the loop after checking the condition.
Example:


package main  
import "fmt"  
func main() {  
   /* local variable definition */  
var a int = 1  
   /* do loop execution */  
   for a < 10 {  
      if a == 5 {  
         /* skip the iteration */  
         a = a + 1;  
         continue;  
      }  
      fmt.Printf("value of a: %d\n", a);  
      a++;  
   }  
}  

Output:

value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 6
value of a: 7
value of a: 8
value of a: 9

On more Example

package main  
import "fmt"  
func main() {  
   /* local variable definition */  
   var a int = 1  
   var b int = 1  
   /* do loop execution */  
   for a = 1; a < 3; a++ {  
      for b = 1; b < 3; b++ {  
         if a == 2 && b == 2 {  
            /* skip the iteration */  
            continue;  
         }  
         fmt.Printf("value of a and b is %d %d\n", a, b);  
      }  
      fmt.Printf("value of a and b is %d %d\n", a, b);  
   }  
}  

Output:

value of a and b is 1 1
value of a and b is 1 2
value of a and b is 1 3
value of a and b is 2 1
value of a and b is 2 3

Go Comments

Single line comment

The compiler and interpreter will not carry out any comments. The comments are used to inform or explain the method, variable, class or statements. It can also be used for a specific time to hide program code. The double forward slash “//” is used for the single-line comment.

Go Multi Line Comment

One or more-line comments are called multiline comments.
Example

package main  
import "fmt"  
func main() {  
   var a int = 10  
   /* Let's declare and 
         print variable in Go*/  
   fmt.Printf("value of a is %d \n", a);  
}  

Go Type Casting

Typecasting means the conversion of a variable from one data type to another. The value may be lost when large type is converted to a smaller type.

package main  
import (  
   "fmt"  
   "strconv"  
)  
func main() {  
  
   var i int = 10  
   var f float64 = 6.44  
   var str1 string = "101"  
   var str2 string = "10.123"  
  
   fmt.Println(float64(i))  
   fmt.Println(int(f))  
  
   newInt, _ := strconv.ParseInt(str1, 0, 64)  
   fmt.Println(newInt)  
  
   newfloat, _ := strconv.ParseFloat(str2, 64)  
   fmt.Println(newfloat)  
}

Output:

10
6
101
10.123

Go Functions

The basic building blocks are functions in Go. A feature is used to disassemble a big problem into smaller tasks. We can use multiple functions; thus, features promote the reusability of the code. Three function types are available: normal functions with an Anonymous identifier or lambda functions the function parameters, return values together with types are called function signatures.

In another function, the function cannot be declared. We can do this anonymously if we want to do this.

Function Prototypes

A function prototype is a declaration of the function that tells the program about the type of value returned by the function and the number and type of arguments.

Function prototyping is one very useful feature of GO function. A function prototype describes the functional interface to the compiler by giving details such as the number and type of arguments and the type of return values.

The prototype declaration looks just like a function definition except that it has no body i.e., its code is missing. This is the time you knew the difference between a declaration and a definition.

A declaration introduces a (function) name to the program whereas a definition is a declaration that also tells the program what the function is doing and how it is doing.

Thus, the above-given examples are function definitions and the following are declarations or shall we say function prototypes:
Example:

package main  
import "fmt"  
type Employee struct {  
   fname string  
   lname string  
}  
func (emp Employee) fullname(){  
   fmt.Println(emp.fname+" "+emp.lname)  
}  
func main() {  
   e1 := Employee{ "Animesh","India"}  
   e1.fullname()  
} 

Output:
Animesh India

How to return something from Function in GO?

package main  
import (  
   "fmt"  
)  
func fun() int {  
   return 123456789  
}  
func main() {  
   x := fun()  
   fmt.Println(x)  
}  

Output:
123

How to return multiple Answers from a function in GO?

See a function example where n type int number is an argument and two int values are returned. In parallel assignment, the return values are specified in the calling function.

package main  
import (  
   "fmt"  
)  
func main() {  
   fmt.Println(addAll(10,15,20,25,30))  
}  
func addAll(args ... int)(int,int)  {  
   finalAddValue:=0  
   finalSubValue:=0  
   for _,value  := range args{  
      finalAddValue += value  
      finalSubValue -= value  
   }  
   return finalAddValue,finalSubValue  
}  

Output:
100 -100

Recursive Function in GO

In Go programming, calling same function from within the function is known as recursion. It is always a good idea to break a problem into multiple tasks. Let us see a program to calculate factorial value in Go programming using recursion.
Example:

package main  
import (  
   "fmt"  
)  
func main() {  
   fmt.Println(factorial(5))  
}  
func factorial(num int ) int{  
   if num == 0{  
      return 1  
   }  
   return num*factorial(num-1)  
}  

Output:
120

Closure in GO

Example:

package main  
import (  
   "fmt"  
)  
func main() {  
   number := 10  
      squareNum := func() (int){  
      number *= number  
      return number  
   }  
   fmt.Println(squareNum())  
   fmt.Println(squareNum())  
}  

Output:

1000

Array in Go Language

In Go, an array is a homogeneous (fixed type) data structure with a fixed length. The type may be integers, strings or self-defined.
You can access the items in the array via its index, it starts from scratch. The array number of items is referred to as the array length or size. The array variable declaration shall be fixed and declared.

Syntax:

var identifier [len]type 

Example:

package main  
import "fmt"  
func main() {  
   var x [5]int  
   var i, j int  
   for i = 0; i < 5; i++ {  
      x[i] = i + 10  
   }  
   for j = 0; j < 5; j++ {  
      fmt.Printf("Element[%d] = %d\n", j, x[j])  
   }  
}  

Output:
Element[0] = 10
Element[1] = 11
Element[2] = 12
Element[3] = 13
Element[4] = 14

Go Multi-Dimensional Arrays

learn go language Array
learn to go language Array

Multi dimensional arrays is simply a list of one-dimensional arrays.
The array can hold multiple values and can be used consecutive space in the memory. It is one of the major drawbacks of array but it also has benefit.

How does an Array work?

learn go language Array
learn go language Array
a = [2][3]int{    
   {2, 4, 6} ,   /*  initializers for row indexed by 0 */  
   {8, 10, 12} ,   /*  initializers for row indexed by 1 */  
}  

Example:

package main  
import "fmt"  
func main() {  
   /* an array with 3 rows and 3 columns*/  
   var a = [3][3]int{ {1,2,3}, {4,5,6}, {7,8,9}}  
   var i, j int  
   /* output each array element's value */  
   for  i = 0; i < 3; i++ {  
      for j = 0; j < 3; j++ {  
         fmt.Print(a[i][j] )  
      }  
      fmt.Println()  
   }  
}  
Benefits of Array in Go:
  • Arrays represent multiple data items of the same type using a single name.
  • In arrays, the elements can be accessed randomly by using the index number.
  • Arrays allocate memory in contiguous memory locations for all its elements.
Disadvantages of Array in Go:
  • Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in GO is not dynamic.
  • Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.

Go Slice

On Go, the slice is a segmented view of a subdivided array in dynamic size. The whole array or subset of the array may be this segment. By indicating the start and end index, we define the subset of an array. Slices provide the sub-array with a dynamic window.
Example:

package main  
import (  
   "fmt"  
)  
func main() {  
   odd := [6]int{2, 4, 6, 8, 10, 12}  
   var s []int = odd[1:4]  
   fmt.Println(s)  
}

Output:

[4 6 8]

one more Example

package main  
import "fmt"  
func main() {  
   names := [4]string{  
      "John",  
      "Animesh",  
      "Jack",  
      "India",  
   }  
   fmt.Println(names)  
   slice1 := names[0:2]  
   slice2 := names[1:3]  
   fmt.Println(slice1, slice2)  
   slice2[0] = "ZZZ"  
   fmt.Println(slice1, slice2)  
   fmt.Println(names)  
}

Output:
[John Animesh Jack India]
[John Animesh] [Animesh Jack]
[John ZZZ] [ZZZ Jack]
[John ZZZ Jack Ani]

Slice Literal

Slice literal is like an array literal without any length.
Example:

package main
import "fmt"
func main() {
   s := []struct {
      i int
      b bool
   }{
      {1, true},
      {2, false},
      {3,true},
      {4, true},
      {5, false},
      {6, true},
   }
   fmt.Println(s)
} 

Output:
[{1 true} {2 false} {3 true} {4 true} {5 false} {6 true}]

Slice Length and Capacity

We typically use command-line arguments when we need to execute a program with some arguments. The Go program can receive and use the arguments passed from the console as an input.
The os.Args is used for argumentation purposes. The 0 indexes of os. Args includes the programme’s path.
Example:

package main  
  
import (  
    "fmt"  
    "os"  
)  
func main() {  
    var s, arg string  
    for i := 1; i < len(os.Args); i++ {  
        s += arg + os.Args[i]+" "  
    }  
    fmt.Println(s)  
}

Output:
1. go build ProgramName.go

Structures in GO

On Go, you can make user-defined types by use of Struct.

The struct is a composite type, which means that each property can have different properties and each has its own type and value.

With these properties, Struct can be a real-world entity. As a single entity, we can access property data. It also has valued types and the new) (function can be built.
Example:


package main  
import (  
   "fmt"  
)  
type person struct {  
   firstName string  
   lastName  string  
   age       int  
}  
func main() {  
   x := person{age: 30, firstName: "John", lastName: "Anderson", }  
   fmt.Println(x)  
   fmt.Println(x.firstName)  
}  

Output:
{John Anderson 30}
John
one more example


package main  
import (  
   "fmt"  
)  
type person struct {  
   fname string  
   lname string}  
type employee struct {  
   person  
   empId int  
}  
func (p person) details() {  
   fmt.Println(p, " "+" I am a person")  
}  
func (e employee) details() {  
   fmt.Println(e, " "+"I am a employee")  
}  
func main() {  
   p1 := person{"Raj", "Kumar"}  
   p1.details()  
   e1 := employee{person:person{"John", "Ponting"}, empId: 11}  
   e1.details()  
}

Output:

{Raj Kumar} I am a person
{{John Ponting} 11} I am a employee

Interfaces in GO

Go has various approaches to implement object-orientation concepts. Go has no classes and no legacy. Through its powerful interface, meet these requirements.

Interfaces provide an object with behavior, which can be used here if something can.

An interface defines a number of abstract methods and has no variable.
Syntax:


type Namer interface {  
             Method1(param_list) return_type  
             Method2(param_list) return_type  
             ...  
}  

another example

package main  
import (  
   "fmt"  
)  
type vehicle interface {  
   accelerate()  
}  
func foo(v vehicle)  {  
   fmt.Println(v)  
     
}  
type car struct {  
   model string  
   color string  
}  
func (c car) accelerate()  {  
   fmt.Println("Accelrating?")  
     
}  
type toyota struct {  
  model string  
   color string  
   speed int  
}  
func (t toyota) accelerate(){  
   fmt.Println("I am toyota, I accelerate fast?")  
}  
func main() {  
   c1 := car{"suzuki","blue"}  
   t1:= toyota{"Toyota","Red", 100}  
   c1.accelerate()  
   t1.accelerate()  
   foo(c1)  
   foo(t1)  
}  

Output:

Accelrating…
I am toyota, I accelerate fast…
{suzuki blue}
{Toyota Red 100}

Go Pointers

Instead of passing a copy of the variable that can reduce memory consumption and increase the effectiveness, we may pass a reference to a variable (for example, as a parameter to a function).
Example:

package main  
import (  
   "fmt"  
)  
func main() {  
   x:=10  
   changeX(&x)  
   fmt.Println(x)  
}  
func changeX(x *int){  
   *x=0  
}

Output:

x = 0
Practice Questions of GO

Areas of Rectangles
The area of a rectangle is the rectangle’s length times its width. Write a program that asks for the length and width of two rectangles. The program should tell the user which rectangle has the greater area, or if the areas are the same.
Mass and Weight
Scientists measure an object’s mass in kilograms and its weight in newtons. If you know the amount of mass of an object in kilograms, you can calculate its weight in newtons with the following formula:
weight mass 9.8
Write a program that asks the user to enter an object’s mass, and then calculates its weight. If the object weighs more than 1,000 newtons, display a message indicating that it is too heavy. If the object weighs less than 10 newtons, display a message indicating that it is too light.
Magic Dates
The date June 10, 1960, is special because when it is written in the following format, the month times the day equals the year:
6/10/60 Design a program that asks the user to enter a month (in numeric form), a day, and a two-digit year. The program should then determine whether the month times the day equals the year. If so, it should display a message saying the date is magic. Otherwise, it should display a message saying the date is not magic.
Color Mixer
The colours red, blue, and yellow are known as the primary colors because they cannot be made by mixing other colors. When you mix two primary colors, you get a secondary color, as shown here: When you mix red and blue, you get purple.
When you mix red and yellow, you get orange. When you mix blue and yellow, you get green.

Counting Game

Create a change-counting game that gets the user to enter the number of coins required to make exactly one dollar. The program should prompt the user to enter the number of pennies, nickels, dimes, and quarters. If the total value of the coins entered is equal to one dollar, the program should congratulate the user for winning the game. Otherwise, the program should display a message indicating whether the amount entered was more than or less than one dollar.

Analyse the problem, design unambiguous and precise algorithm and code for each of the following problems.

  1. Compute the cost per square foot of living space for a house, given the dimensions (Length, Width) of the house, the number of stories, the size of the non-living space (garage, closets), the total cost of the house.
  2. Given a positive integer number, find whether the number is even or odd.
  3. Given a positive integer number, find display if the number is a prime number.
  4. Find the slope of a line through two points using formula m = . The values of y1, y2, x1 and x2 are given. If x1 equals x2, the line is vertical and the slope is undefined. If y1 equals y2, the line is horizontal.
  5. Write a code to calculate and print the diameter, the circumference, or the area of a circle given the radius. The input is two data items. The first is a character – ‘D’ (for diameter), ‘C’ for circumference, or ‘A’ for area – to indicate the calculation needed. The next data value is a floating-point number indicating the radius of the particular circle.
  6. A company manufactures a line of traffic cones. It requires painting its cones in different colours. The company has hired you to write a program that will compute the surface area of the cone, and the cost of painting it, given its radius, height and the cost per square foot of three different colours of paint. The surface area of the cone can be calculated using formula
  7. Mother had just filled the cookie jar when the three children went to bed. That night one child woke up, ate half of the cookies and went back to bed. Later, the second child woke up, ate half of the remaining cookies and went back to bed. Still later, the third child woke up, ate half of the remaining cookies, leaving 5 cookies in the jar. How many cookies were in the jar to begin with? Find a generic solution to this problem.
  8. Find and display the sum of numbers from 1 to n where n is input by the user.
  9. Display a line of n stars.
  10. Input an integer value and if the input value is equivalent to the value of a British coin, print it out in words. Otherwise it should print an error message.

Input Print

1 One Penny

2 Two Penny

5 Five Penny

10 Ten Pence

50 Fifty Pence

  1. Add a series of numbers input by the user and find the average of these numbers. It is not known in advance how many values will be input.
  2. Display the status of the students (Pass or Fail) based on the marks entered by the user. It is not known in advance how many marks will be entered.
  3. Find the hypotenuse of the right-angled triangle given its two sides using Pythagorean Theorem.
  4. Write a program that reads the lengths of the sides of a triangle from the user and computes and displays the area of the triangle using Heron’s formula. The Heron’s formula is:

Where A, B, C are three sides of a triangle and S is half perimeter and is calculated by

  1. Given the cost of sales item, calculate the amount of sales tax and total cost of the sales item including tax assuming 7% sales tax.
  2. A person’s weekly pay is Rs. 2500/-. He is scheduled to receive a 3% pay raise next week. Calculate the amount of his new salary.
  3. In a video store a daily rental fee of a video is Rs. 50/-. Customers are charged a late fee of Rs. 20/- per day when the video is returned past the due date. Assume that a customer can return only one video at a time, calculate the amount the customer owes when he/she returns the video.
  4. Given a positive integer number N, find display all the prime number that are less than or equal to N.
  5. A woman is going shopping to buy fifteen items only. Find the total cost of these fifteen items given the price of each item. Also display the highest price and the lowest price.
  6. A perfect number is a positive integer such that the sum of proper divisors equals the number. Thus 28 = 1 + 2 + 4 + 7 + 14 is a perfect number. If the sum of proper divisors is less than the number, it is deficient. If the sum exceeds the number, it is abundant. Write a program that allows the user to enter a positive integer N and then displays all perfect, deficient, and abundant numbers less than or equal to N.


Spread the love
I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on ani01104@gamil.com

6 COMMENTS

  1. […] Learn Go Language Step by Step Fast and Simple Way Read More » […]

  2. […] Learn Go Language Step by Step Fast and Simple Way in 2020 Read More » […]

  3. […] Learn Go Language Step by Step Fast and Simple Way in 2020 Read More » […]

  4. What’s Happening i am new to this, I stumbled upon this I’ve found It positively useful and it has aided me out loads. I hope to contribute & aid other users like its helped me. Good job.

LEAVE A REPLY

Please enter your comment!
Please enter your name here