Kick Start – golang

There are many reasons to learn and use golang in current projects. Do you want to start your golang journey? Well, let’s kick start ! I have created a repo to add few samples of golang codes which may help you in your journey.Feel free to connect me if you need any help on golang projects.
You can start your golang 101 with below bubble sort example. Keep following my repo for further sample push

package main

import "fmt"

func main() {

    /* Array for sorting */
	var numbers = []int{5, 6, 8, 10, 23, 6, 7, 7, 7}
	var i, j int

	for i = 0; i < len(numbers)-1; i++ {
		for j = i + 1; j < len(numbers); j++ {
			if numbers[i] > numbers[j] {
				var temp = numbers[i]
				numbers[i] = numbers[j]
				numbers[j] = temp
			}
		}
	}

	for j = 0; j < len(numbers); j++ {
		fmt.Printf("%d,", numbers[j])
	}
}


How Goroutines communicate to perform a common goal

synchronized(lock){
    while(!condition){
        lock.wait();
    }
}

Code constructs like “synchronized”,”Lock”,”wait()”,”notify()” are not new for us. From decades we are coding with similar Legacy constructs that play a key role in multithreading codes. The Legacy term! 🙂 Yes, you read it correctly! When you try similar code with Go, code is very precise, compact, friendly and superfast. Lets see why Go executes multithreading (let me correct here GREEN THREADs) code faster than others. Because there is no Thread concept in Go, instead it has Green Threads.

For deeper concepts connect me in linked.

Here I have illustrated how two Goroutines are communicating with each other through channel to print Odd and Even numbers alternatively. This may give you little insight if you are planning to write new microservices ( especially for very huge data processing and scalable products like IoT etc.. then you can think of Go!

/**
 * @author Gyanendra
 * @Date : 02/03/20
 */
package main

import (
	"fmt"
)

func main() {

	numFlag := make(chan int)
	done := make(chan bool)
	go oddNumberRoutine(numFlag, done)
	go evenNumberRoutine(numFlag, done)
	<-done
}

func oddNumberRoutine(numNeedToBePrinted chan int, printingCompleted chan bool) {

	for {
		v := <-numNeedToBePrinted
		if v >= 20 {
			printingCompleted <- true
			break
		}
		fmt.Println("Odd ==>", v)
		numNeedToBePrinted <- v + 1
	}

}

func evenNumberRoutine(numNeedToBePrinted chan int, printingCompleted chan bool) {
	numNeedToBePrinted <- 1
	for {
		v := <-numNeedToBePrinted
		if v > 20 {
			printingCompleted <- true
			break
		}
		fmt.Println("Even ==>", v)
		numNeedToBePrinted <- v + 1
	}

}

Odd ==> 1
Even ==> 2
Odd ==> 3
Even ==> 4
Odd ==> 5
Even ==> 6
Odd ==> 7
Even ==> 8
Odd ==> 9
Even ==> 10
Odd ==> 11
Even ==> 12
Odd ==> 13
Even ==> 14
Odd ==> 15
Even ==> 16
Odd ==> 17
Even ==> 18
Odd ==> 19
Even ==> 20

Get this code from my repo