Go Tutorial for Beginners 

What is Golang?

Go is commonly known as Golang is a programming language. It is a freeware programming language originally developed at Google. It allows parallel programming, i.e. multiple programs are executed concurrently. The Syntax of Go Programming Language is identical to C Programming Syntax. It supports garbage collection and contains many built-in functions. The program execution procedure used in GoLang is identical to that of C Programming.

Features of Go

The best features of Go are as follows:

  1. The time required for compiling a Go Program is very low.
  2. The Go Programming Language is Platform Independent.
  3. It supports Type Embedding and Interfaces.
  4. It has inbuilt library functions.
  5. Go Programs are simple and brief.

Now let us discuss the programming structure of Go Programs.

Basic Structure of Go Programs

Every Go Program Contains the following Parts

  1. Declaration of Packages
  2. Package Importing
  3. Functions
  4. Variables
  5. Expression and Statements
  6. Comments

Let us see a sample Go Program.

package Mind  // Declaration of Package

import “go1”  // Importing Package

func main()  // main() function

{

Go1.println(“ Hello World”)

}

In the above program, we have the following statements:

  1. In the first Statement, we have defined a package called “mind”, and our program should be stored in that Package.
  2. In the second statement, we have imported a package called “go1”, and the files present in that package are included in our program.
  3. In the next line, we have declared the main() function, and from there, program execution begins.
  4. In the main() function, we have a println function which makes “Hello World” message displayed on the screen.

After writing the program, we have to execute the program. Let us see the procedure for executing a program.

Go Program Execution

For Executing a Go Program, we have to follow the below statements:

  • Step1) Write the Go Program in a Text Editor.
  • Step2) Save the program with “.go” as the program file extension.
  • Step3) Go to command Prompt.
  • Step4) In the command prompt, we have to open the directory where we have saved our Program.
  • Step5) After opening the directory, we have to open our file and click enter to compile our code.
  • Step6) If no errors are present in our code, then our program is executed, and the following output is displayed:
“Hello World”

Data Types

Data types are used to declare variables and functions. Data types indicate how much space should be allocated to a data member like variables, functions, etc. In Go Programming language Data types are classified into different types:

1. Boolean Types

The Boolean Type variables will take only two values they are: 1) True 2) False.

2. Numeric Types

Data types like Integer, float come under this type. The Numeric type variables store only numerical values. 

3. String

A String data type takes a collection of string values. The values once stored in the string variable cannot be deleted.

4. Derived Types

In Go Programming language, we have different derived types, they are: i) Arrays ii) Pointers iii) Unions iv) Structures v) Interfaces vi) Functions.

Type Casting

Typecasting is a mechanism to change the data type of a particular variable. For example, if we store decimal values into an integer variable, we have to change the data type of that variable to float32.

Example

package mind

import “go1”
 
func main()

var a int = 10
var b int = 3
var c float32

c = float32(a) / float32(b) // converting the datatype of variables a and b from int to float32

go1.println(“ value of c is : %f “ ,c)

The output of the above program is ;

Value of c is: 3.3333

The integer variables a and b are converted into float variables.

Variables

A Variable is defined as a name mentioned to a memory location that the program can control. In Go programming language, every variable will have a data type, which indicates how much memory is required for storing that variable.

Variable Declaration

A Variable Declaration indicates the compiler how much memory should be created for storing that variable. The Syntax for Variable Declaration is as follows:

 Var Variable_list1 optional_data_type;

In the above statement, the optional_data_type contains Go data types like int, string, float, boolean, etc. The variable_list1 comprises the list of variables.

Example:

var a, b, c float;
var e, f, g int;

Variable Initialisation

At the time of declaring a variable, they can be initialised with certain values. According to the values initialised to the variable, the compiler evaluates the data type of that variable. Variables are initialised through the assignment operator “=”. The syntax for a variable initialisation is as follows:

Variable = value;

Example

i=7, k=3;

Static Type Declaration

The Static type variable declaration gives the compiler that only one variable exists with the given name and types such that the compiler can continue further compilation excluding other details of the variable.

Dynamic Type Declaration

In the Dynamic Type Declaration of a variable, the compiler has to evaluate the type of the variable according to the value initialised to it.

Example

package mind

import “go1”

func main() {

Var z int = 30;

i := 75;

go1.println(z);
go1.println(i);
go1.println(“ z data type is %Tn”, z);
go1.println(“ i data type is %Tn”, i);
}

30
75
z data type is int
i data type is int

Scope of Variables

The scope of variables tells us where we can access a variable and where we cannot access a variable. Based on the scope, the variables are classified into two types: they are:

Local Variables

These variables are declared inside a block or a function. They are accessed by the statements which exist in that module or function.

Global Variables

Generally, global variables are declared at the topmost part of the program. so, they can be accessed by any statement present in that program

Constants

Constants are defined as permanent values such that programs may not change them at the time of program execution. While declaring constants, we should use the “const” keyword.

Example:

Package mind

import “go1”

func main() {

const side int = 12
var ar int

ar = side*side

go1.println(“ Area of square is : %d “, ar)
}

Output:

Area of square is: 144 

Operators

An operator Symbolically tells the compiler to do particular arithmetic or logical operation. The Go Programming language supports the following operators:

  • Arithmetic operators
  • Logical operators
  • Assignment operators
  • Bitwise operators
  • Relational operators
  • Miscellaneous operators

1) Arithmetic operators

In Go programming language, we have several arithmetic operators. They are as follows: Let us imagine that we have two integer variables like C=10, d=50.

a. Addition “+” operator

The addition operator is used to add two operands. 

Example:

C+D=60

b. Subtraction “-” operator

The subtraction is used to subtract the second operand from the first operand.

Example:

D-C=40

c. Multiplication ‘*” operator

The multiplication operator is used to multiply two operands. 

Example:

C*D=500

d. Division “/” operator

The division operator is used to divide the numerator with the denominator.

Subscribe to our youtube channel to get new updates..!

Example:

D/C= 5

e. Modulus “%” operator

The Modulus operator is applied to return the remainder after the division operation.

Example:

D%C=0

f. Increment “++” operator

The increment operator is applied to increase the value of a specific variable.

Example:

C++ = 11

h. Decrement “--” operator.

Example:

D-- = 49

The decrement operator is applied to decrease the value of a specific variable. 

2) Logical Operators

The Go Programming language supports different logical operators who are as follows:

a. AND Operator

The logical AND operator is indicated by the “&&” symbol. When both operands contain non-zero values, then the result becomes true.

b. OR Operator

The logical OR Operator is indicated by the “||” symbol. When any one of the two operands is true, then the result will be true.

c. NOT Operator

The NOT Operator is indicated by the “!” symbol. It will make the complement of the given input.

3) Assignment Operators

The Go programming language supports different assignment operators; they are as follows:

a. Equal to “=” operator

The “=” operator is used to assign the values present in the left operand to the right operand.

Example:

C+D=E

b. Addition AND “+=” Operator

The “+=” operator is used to add the right operand to the left operand, and then the result is assigned to the left operand.

Example:

C+=E is equal to C=C+E

c. Subtraction AND “-=” Operator

The “-=” operator is used to subtract the right operand from the left operand, and then the result is stored in the left operand.

Example:

C-=E is equal to C=C-E

d. Multiplication AND “*=” Operator

The “*=” Operator is used to multiply the left operand with the left operand, and then the result is assigned to the left operator.

Example:

C*=E is equal to C=C*E

4) Bitwise operators

 The working of Logical operators is the same as Logical Operators. The truth tables for Bitwise operators are as follows:

a. Bitwise AND

C D C AND D
0 0 0
1 0 0
0 1 0
1 1 1

b. Bitwise OR

C D C OR D
0 0 0
1 0 1
0 1 1
1 1 1

Bitwise Exclusive OR

C D C EXCLUSIVE OR D
0 0 0
1 0 1
1 1 0
0 1 1

5) Relational Operators

Relational operators are used to evaluating the relationship between the two operands. The different relational operators are as follows:

a. Equal to “==” operator.

The equal to the operator is used to check whether the value of the left operand is equal to the value of the right operand or not. If they are equal, then the result will be true; otherwise, it will be false. 

b. Not Equal to “!=” operator.

The “not equal to” operator is used to check whether the value of the left operand is equal to the value of the right operand or not. If they are not equal, then the result will be true; otherwise, it will be false.

Other relational operators are 1) Greater than(>) 2) Lesser than(<) 3) Greater Than or equal to(>=) 4) Lesser than or equal to(<=).

6) Miscellaneous operators

The Go Programming Language Supports two Miscellaneous operators, they are 

a. “&” operator

The “&” operator is used to store the address of a particular variable.

Example: &a

b. “*” operator

The “*” operator is used to refer a pointer variable.

Example: *a

Conditional Statements

The conditional statements are also called decision-making statements. In Decision-making programs, the statements are executed depending upon the condition specified. If the condition is true, one statement is executed. Otherwise, another statement is executed. In Go Programming language, we have different conditional statements are as follows:

1.  If Statement

 syntax of “If” statement is :

if(condition){

Statement1;

}

Statement2;

In the above code, if the condition present in the “if” block is true, then the statement1 is executed; otherwise, statement2 is executed.

2. If-else Statement

The syntax of If-else statement is as follows:

if(condition){

Statement1;

else

Statement2;

}

In the above code, if the condition present in the “if” block is true, then the statement1 is executed; otherwise, statement2 is executed.

Example

package mind

import “go1”

func main() {

Var c=15 int

if(c<10) {

go1.println(“ value of c is less than 10”)        

else

go1.println(“value of c is greater than 10”)

}

}

3. Nested If statement

The syntax of "Nested If" statement is as follows:

If(Condition-1) {

statement1

if(Condition-2) {

Statement2

}

}

In the above code, one if "statement" is placed inside another if statement. When condition-1 is true, statement1 is executed, and condition-2 is checked. If the condition-2 is true, then statement-2 is also executed.

4. Switch Statement

The switch statement tests the variable by supplying different values. The syntax of the switch statement is as follows:

switch(expression)

{

Case-1

Statement

break;

Case-2

Statement

break; 

Case-3

Statement

break;

}

5. Select Statement

Select Statement is identical to switch statement; the only difference is case refers to the channel communications.

6. Loop or Iterative Statements

The Loop or iterative statement enables the programmer to execute the same statement multiple times. In Go Programming Language, we have different loop statements; they are as follows:

For loop

The for loop executes a series of statements repeatedly. The syntax of for loop is as follows:

for( variable initialisation; condition checking; Increment/Decrement){

Statement1;

}

Example

package mind

import “go1”

func main() {

var c int

for (c=0; c<=10;c++)

{

go1.println(c);

}

}

Nested Loops

In Go Programming, nested loops provide the facility to run multiple loops inside another loop.

Strings

In Go Programming Language, strings are also known as slices. Strings are defined as collections of bytes. Strings can be created as follows:

var  =  “Welcome to you”

Manipulation Functions of String

In Go Programming, we have the following Manipulation functions:

Len(str)

This manipulation function is used to determine the length of a string.

Concatenate

This manipulation function is used to join or merge two strings.

Arrays

The array is a data structure which stores a fixed size of elements in sequential order. An arrays stores the elements which have the same data type. The array comprises contiguous memory locations. 

Array Declaration

In Go Programming, we can declare the array as follows;

var variable_name1 [size] data_type

Example:

var A[10] int

The above statement says that an array named “A” stores ten integer elements. The above array is a single or one-dimensional array.

Array Initialisation

In Go Programming an array can be initialised as follows:

Var A = [10] int {225, 475,355, 155, 635, 985, 555, 765, 895, 1015}

The elements of an array are accessed through their indexes. 

Example:

Int a= A[5]

The above statement says that the fifth element of the “A” array, is stored in the integer variable “a”.

The Go Programming Language Supports multidimensional arrays. In a multidimensional array, we will have multiple indexes.

Functions

A function is a self-contained program or a module in the program. It contains certain statements to do a specific task. The syntax of the function is as follows:

func function_name1 ( [list of parameters] ) [ return_type]

{

function_body

}

In the above code, we have:

  • func: with this keyword, the function declaration begins.
  • function_name1: This is the real name of the function. The name of the function depends on the operation it performs. 
  • Parameters list: The parameters act as input to the function. It will perform the operations on the given parameters.
  • Return_type: The return type specifies the data type of the values the function returns.

Function Calling

A program calls the function to do a particular task. After doing that task, the function will return the result through the return keyword.

1. Parameter Passing Mechanism

In Go Programming, we can pass the parameters from the calling function to the called function. The parameters present in the calling function are called Actual Parameters and the parameters present in the called function are called Formal Parameters. There are two ways of Parameter Passing; they are:

  • Call-by-value

In this method, the values of the actual parameters are passed to the formal parameters. The changes done to the formal parameters are not reflected in the actual parameters.

  • Call-by-Reference

In this method, the addresses of actual parameters are passed to the formal parameters. The changes done to the formal parameters are reflected in the actual parameters.

2. Recursion Function

The function which calls itself is called a recursive function. Example of a recursive function is as follows:

package mind

import “ go1”

func fib1( a int) int {

 if(a<=1) {

 return 1

}

return fib1(a-1)+fib1(a-2)
}

func main() {

Var c int =3

go1.printf(“ Fibonacci series is %d “ fib1(c))
}

Pointers

The pointer is a variable that stores the address of another variable. The pointer variables can be declared as follows:

var var1_name *var1_type

In the above statement, var1_name is the name of the pointer variable, and var1_type is the data type of the pointer variable. The asterisk symbol indicates that the declared variable is a pointer variable. 

Example:

Var d *int

We have declared an integer pointer variable.

As we have said that a pointer variable stores the address of another variable, Now let us see how it will store the address of another variable.

Var c int = 25  

We have declared an integer variable “c.”

Var e *int

We have declared an integer pointer variable “e.”

e = &c

By using the “&” symbol, we have stored the address of the variable “c” into pointer variable “e”.

Note: The data type of the pointer variable and the data type of the variable of which the address is stored in that pointer variable should be the same.

Structures

Structures is another data type that exists in Go Programming. They are used to declare a record in the program. To declare a structure, we should use struct and type statements. The struct statement acts as a data type for structures. Example of a structure is as follows:

type student struct {

id int

name string

percentage float64

rank int

}

In the above code, a structure called “student” is declared. The data members of that structure are: 1) id 2) string 3) percentage 4) rank. Depending on the values they store, we have assigned the data types to the data members. For example, the 

Percentage of a student can be ‘94.0” or ‘94.5”, so we have assigned the “float64” data type to it. 

Accessing Structure Members

The data members of a structure are accessed using dot “.” operator. For accessing structure members, we will create structure variables.

Example:

ar stud1 student

We have created a structure variable called “stud1”; through this, we will access the structure members.

stud1.id

stud1.name

stud1.percentage

Stud1.rank

Error Handling

In every program, we will face some errors during the execution of the program or after the execution of the program. To handle those errors in Go programs, we have a simple inbuilt framework. To build an error message, we use “errors.New”.

Interfaces

Go Programming language supports interfaces to include methods in the Go Programs.  Structures use methods to access data members.

Conclusion

Go Programming Language is used for solving general problems like arithmetic, Logical, etc. The syntax and concepts of Golang are similar to those of C and java. It uses object-oriented concepts like packages, interfaces for developing programs. It can be used as an alternative to C and Java. Any non-technical person can learn Go Programming Language easily.