99devops

99devops

A highly trained monkey’s blog

17 Oct 2021

Let's get going - Day 1

go

As per the weekly Get Going session, today we will be looking into some go basics which will help you cover the basics of go applications and move forward in creating complex applications in go.

Today we will be looking into followings

Table of contents

  1. Commenting in Go
  2. Variables and Constants
  3. Integer, Float, Strings and Rune
  4. Operations
  5. Array, Slice and Maps data
    1. Array
    2. Slice
    3. Map

Commenting in Go

In Go comments are written as // for single line comment and /* */ for multi line comment.

// Single line comment

/*
This is a
Multi line comment
*/

Tips: It is good to comment your functions so that it can be view as part of function when you hover mouse over it. eg: if you write function like this and hover mouse over the function usage in part of code, it will show the function documentation there making it easy to know what that function what and it’s usage.

// When you comment over function like this, it can be seen when mouse is hovered over
// the function making it easy to read what function does
func adder() {
}

Above will be shown like this

comment

Variables and Constants

Go is staticaly typed programming language hence variable type must be explicitly declared. When creating a varible there are two step, first one is declaring variable ( declare what type ) and second is initializing ( initialize value). You can declare variable like this

var [variable_name] [variable type]

eg:

var myName string
var age int

If the value to the variable is given at declaration then Go will automatically infer the variable type. For example if you declare variable like this var age = 2 then it auto detects it is a variable of type int or if you declare variable like this var name = "prabesh" then it auto detects it is a variable of type string which is neat.

You can also assign multiple variable at once like this

var value, status = "12", true

Variable can be declared to be used later in programs without assigning values to them. When a valiable.

When a variable is declared without assigning value then by default they will hold empty value i.e. if you declare int variable then by default its value will be 0 and if you delare a string variable then it will hold empty string not nil.

Variable can be declared and initialized using short hand version as well using := operation. This mean you are declaring and initializing a variable i.e. var age int = 2 can be written as age := 2. This makes things a lot easy.

Constants can be declared using const operator. Unlike variable, their value cannot be changed through out the program. A constant is declared like this

const pi float32 = 3.1415

Integer, Float, Strings and Rune

Integer in go can be declared by adding int type to the variable declaration like this var age int = 24

Floating point number can be declared by adding either float32 or float64 type in the variable declaration like this var pi float32 = 3.14 or var pi float64 = 3.1415. float32 uses 32 bits of memory and stores value in single floating point format where as float64 uses 64 bits in memory and stores values in double floating point format.

Similar to other language strings are the collection of character. eg "This is a string" is a string with multiple character and "a" is also a string with single character ( including the double quotes).

If you represent "a" like this 'a' ( notice the single quote), then it is called a rune where that character can be represented in Unicode code points.

package main

import (
	"fmt"
)

func main() {
	var age int = 22 // Integer
	var pi float32 = 3.14 // Floating point number
	var double_float float64 = 3.141562 // Double float
	
	fmt.Println(age)
	fmt.Println(pi)
	fmt.Println(double_float)
	

	rune := 'a'
	string_with_single_char := "a"
	string_with_multiple_char := "Prabesh"
	
	// This prints unicode code point
	fmt.Println(rune)
	
	// This prints out character
	fmt.Println(string_with_single_char)
	
	// This prints out string with multiple char
	fmt.Println(string_with_multiple_char)
}

You can run and see the output here

Operations

There are various operations that we can do in programming i.e add, subtract, divide, multiple, calculate remainder etc. Let’s see how to do these. This is similar to other programming language.

package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println("Addition", 1+2)
	fmt.Println("Subtraction", 4-3)
	fmt.Println("Multiple", 3*2)
	fmt.Println("Division", 22/7) // This will give output in integer as it is integer operation. 
	fmt.Println("Division", 22.0/7) // For floating point operations js8ut add ".0" at end
	
	fmt.Println("Exponential", math.Pow(20.0, 3))
	fmt.Println("Reminder", 3%2)
	
	// Boolean operations
	fmt.Println("Greater than", 2 > 1)
	fmt.Println("Greater than", 1 > 2)
	fmt.Println("less than", 1 < 2)
	fmt.Println("Greater or quivalent", 2 >= 1)
	fmt.Println(4.0 == 4)
}

You can run the code here

Array, Slice and Maps

Similar to other programming language collections of data types can be done in various ways. They are described below one by one

Array

Array can be declared in go like this [name_of_array] := [length_of_array][array_type]{values} ( notice the curly braces). An array can have values with same data type. An example can be seen below

package main

import (
	"fmt"
)

func main() {
	students := [3]string{"prabesh","pradip","asmita"}
	fmt.Println(students)
}

Array can be defined without initializing before like variables and added later using the index like this array_name[index]. eg

package main

import (
	"fmt"
)

func main() {
    movies := [3]string{} // Defined array of type string
	
	// Adding values later to the array using the index
	movies[0] = "50 Shades of Grey"
	movies[1] = "X-men"
	movies[2] = "Pokemon"
	
	// Accessing individual element
	fmt.Println(movies[2])
	
	// Accessing whole array
	fmt.Println(movies)
}

If no value is added in the arry the it will take the default value i.e if you declare array on int with 3 length and added value to first and not on remaining two then they will hold default value. Default values are

int = 0 
float = 0.0
string = ""

length of array can be accessed using built-in len function.

You can run the code here

You can also create multi-dimensional array as well like this

rectangle_coordinates := [2][2]int{}

Slice

Slices are used when you are not sure about the size of the array of when the size of array is not known. Creating slice is similar to creating array, you just do not specify the length.

You can declare a slice like this

surnames := []string{}

and append to that slice using append function

	surnames = append(surnames, "Thapa")
	surnames = append(surnames, "Silwal")
	surnames = append(surnames, "Adhikari", "Tamang") // can do this also

example

package main

import (
	"fmt"
)

func main() {
	// Slice = variable length array
	surnames := []string{} // Declaring slices
	
	surnames = append(surnames, "Thapa")
	surnames = append(surnames, "Silwal")
	surnames = append(surnames, "Adhikari", "Tamang") // Can append multiple data at once.
	
	fmt.Println(surnames)
}

You can also create a slice of fixed length using make method. eg:

package main

import (
	"fmt"
)

func main() {
	// Slice = variable length array
	surnames := []string{} // Declaring slices
	
	surnames = append(surnames, "Thapa")
	surnames = append(surnames, "Silwal")
	surnames = append(surnames, "Adhikari", "Tamang") // Can append multiple data at once.
	
	fmt.Println(surnames)

	movies := make([]string, 4) // Creating a slice with a default value of 4
	movies[0] = "He-man"
	movies[1] = "Ant man"
	movies[2] = "Iron man"
	movies[3] = "Hulk"

	fmt.Println(movies)
}

You can run the code here

Slice supports usage of slicing operation : with syntax `slice_name[low:high]

Map

Maps are similar to dicts in other programming languages. You can define a map using hte map keyword like this map[type_of_key]type_of_value eg

student := map[string]string{
	"name":    "prabesh",
	"address": "11 nsw str",
	"phn_no":  "1246322562",
}

You can just declare map only as well without any values

ages := map[string]int{}

Addition is similar to adding an item in an array but this time you use the key instead of the index number.

ages["kabita"] = 68
ages["pradip"] = 21
ages["prabesh"] = 20

Deletion is done using delete method and passing map and its keyword

delete(ages, "prabesh") // delete entry from map

example

package main

import (
	"fmt"
)

func main() {
	// map[type_of_key]type_of_value
	birthday := map[string]string{
		"name":    "prabesh",
		"address": "11 bond str",
		"phn_no":  "0414032050",
	}
	fmt.Println(birthday)

	ages := map[string]int{} // defining map without any pre-values
	ages["prabesh"] = 26
	ages["kabita"] = 68
	ages["pradip"] = 21
	ages["prabesh"] = 20

	delete(ages, "prabesh") // delete entry from map

	fmt.Println(ages)
}

You can run the code here

comments powered by Disqus