Go Lang: The Go Basics

Go Lang: The Go Basics

  • Go is a procedural programming language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language.

  • Go lang is strong and statically typed, meaning variables can only have a single type. It is also a concurrent, and garbage-collected programming language.

  • It is designed to be simple, efficient, and easy to learn, making it a popular choice for building scalable network services, web applications, and command-line tools.

  • Go Lang, is compiled language which means a go code (main.go) is first compiled into an executable file (main.exe) using a compiler. Go has a fast compiler, which makes it easy to iterate quickly during development.

Why Go🏃‍♂️

  • The infrastructure has evolved over the last decade. Multi-core processors were becoming common and the use of cloud servers with thousands of servers and multiple processors was becoming a norm to deploy applications.

  • Here most of the applications failed to take benefit from this infrastructure advancement. Applications were only able to execute one task at a time but infrastructure could enable it.

  • Now many languages like Java, and C++ had features like concurrency and multithreading, but code could get pretty complicated. This is where Go comes into the picture as it is built while keeping in mind the above needs.

  • Go was designed to run on multiple cores and built to support concurrency.

Installation of Go

  1. We need to install VS Code. Download according to the operating system.

Link: https://code.visualstudio.com/Download

  1. We need to download Go. Download according to the operating system.

Link: https://go.dev/doc/install

Click on the installed package . Go with the default settings and install.

After this run the below command in command prompt to check if go is installed or not.

go

If you see below output , this confirms that we have go installed.

Let's Go with the Go code

We need to create a directory where our code will be saved. In command prompt, at you accessible location create a folder

mkdir <Folder_Name>             --This will create a folder
cd <Folder_Name>                --Change directory to that folder
code .                          -- This will open VS COde

Now we need a extension just to make our lives little easier

Go to Extensions -> Go(By Go team at google). Click on install.

  • After the installation is complete, open the command palette by pressing Ctrl + Shift + p

  • Run the Go: Install/Update Tools command

  • Select all the provided tools and click OK

Now let's create a go file(main.go)

Here we can see I have a file go.mod. We require to initalize the module first. We will talk about this further.But why we require go.mod file:

When your code imports packages contained in other modules, you manage those dependencies through your code's own module. That module is defined by a go.mod file that tracks the modules that provide those packages. That go.mod file stays with your code, including in your source code repository.

To enable dependency tracking for your code by creating a go.mod file, run the go mod init command, giving it the name of the module your code will be in. The name is the module's module path.

Run below command.

go mod init <module_path_as_name>

This will create a go.mod file

Let's write a code

The first line of a code is a package name

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello Go!")
}
  1. The first line is where we defined the package of which the code is part.

  2. Next, we import the built-in package "fmt" or format .fmt is a Go package that is used to format basic strings, values, inputs, and outputs. It can also be used to print and write from the terminal.

  3. Next, we need to give a start point to go to start code execution . Hence the execution in go starts from the main function. One go program has only one main function.

  4. Next, we print the Hello Go! This is done by fmt package using a Println function to output the string.

Now let's run this go application

go run main.go                   //this will give output

Variables

Declaring a variable: Variables are declared using the var keyword. For example, to declare a variable called number of type int, you would write:

var <Vairiable_Name> <Data_Type>

For ex:

  1. var number int

  2. var temperature float64=75.4566

Short Assignment operator :

Inside a function (even the main function), the := short assignment statement can be used in place of a var declaration. The := operator infers the type of the new variable based on the value.

So we were declaring variables as

var empty string

now with short assignment operator

empty:=”” …. This is how short assignment operator is used

Another way to declare the variable:

A dynamic type variable declaration requires the compiler to interpret the type of the variable based on the value passed to it. The compiler does not require a variable to have type statically as a necessary requirement.

package main

import (
    "fmt"
)

func main() {
    var student1 string = "John" //type is string
    var student2 = "Jane"        //type is inferred
    x := 2                       //type is inferred

    fmt.Println(student1)
    fmt.Println(student2)
    fmt.Println(x)

}
O/P:
PS V:\Go Programming> go run main.go
John
Jane
2

If the variable is not assigned any value , they take the default value.

var a string
var b int
var c bool

fmt.Println(a)
fmt.Println(b)
fmt.Println(c)

  • a is ""

  • b is 0

  • c is false

Value Assignment After Declaration

package main
import ("fmt")

func main() {
var student1 string
student1 = "John"
fmt.Println(student1)
}

O/P: John

Go Multiple Variable Declaration

var a, b, c, d int = 1, 3, 5, 7

var a, b = 6, "Hello"
c, d := 7, "World!"

var (
a int
b int = 1
c string = "hello"
)

Data Types

  • Boolean Type:

    bool

  • String Type:

    string

  • Numeric Type:

    int int8 int16 int32 int64

    uint uint8 uint16 uint32 uint64 uintptr

    float32 float64

  • byte // alias of uint8

  • rune //alias of int32

    //represent unicode code point

  • complex64 complex128

If we have no specific need its better to go with default ones,

  • bool

  • string

  • int

  • uint

  • byte

  • rune

  • float64

  • complex128

Go Constants

If a variable should have a fixed value that cannot be changed, you can use the const keyword.

The const keyword declares the variable as "constant", which means that it is unchangeable and read-only. Which means when constant is declared it can not be changed later

Rules:-

  • Constant names follow the same naming rules as variables

  • Constant names are usually written in uppercase letters (for easy identification and differentiation from variables)

  • Constants can be declared both inside and outside of a function

Types Constants: Constants declared with Type

Const ABC int=1

Untyped Constants: Declared without type