Golang Concurrency Part II

In Part I, we just converted a sequential program to a multithreaded one and did it with a very simple example. But real world problems are more complex then that. Now assume a server which confirms your login via OTP SMS and same is done for 10000 users per second. Now that’s what I called a problem.

Solution: As a simple design I will create independent jobs, one will handle the login part and other will handle the OTP SMS part. So, SMS job will just run independently of the login job. That’s how SMS job can be reused for other user logins. Now there is a need that both jobs must communicate.

Golang has provided a mechanism known as Channels. I this part of blog I will explain basics of channels.

Channels

In simple words, Channels are the connection between goroutines. Let’s discuss some facts and then a straight forward example will make it clear.

  • Each golang channel has a data type,  like int, string or struct {}. E.g. ca chan int. ca is channel variable and chan int is how we can declare channel.
  • We need to use make() to actually create a channel. e.g. ch := make(chan int). If, we don’t make a channel it cannot be used and will cause panic.
  • We can pass channels as function arguments and they are automatically passed a s reference.

Using A Channel

Channel has three operations defined.

  1. Read. (Eg. ch-<x) // write x to channel ch
  2. Write. (x := <-ch) // read channel into x
  3. Close. (We will discuss close in detail.)

Close

  • If we send on a channel after closing it, panic will occur.
  • If we read from a channel after closing it, first all the unread valued will be read and after that read will always read the zero value of channel.

Kinds of Channel

  1. Unbuffered.
  2. Buffered.

In this part we must stick to unbuffered channel and it’s complexities. In next blog we will take on buffered channel.

Unbuffered channels

Unbuffered channels are also called, Synchronous channels. Because they work in a manner that only one operation can be performed at a time, either Read or Write.

e.g.

ch := make(chan int) is a Unbuffered channel. There are few rules about them.

  1. If channel is not empty, send operation will block. Executing a receive will make channel available for send.
  2. If a channel is empty, receive operation will block. We have to perform send operation.

Example (Toggle Me)

package main

import (
       "fmt"
       "sync"
)
var wg sync.WaitGroup

func toggle(ch <-chan int) {


       for k := range ch { // reads from channel until it's closed
              fmt.Println("================================>" , k*k)
       }

       // this will be called only if we close the channel.. :-)
       wg.Done()

}



func main() {
       // create a channels
       ch1 := make(chan int)
       ch2 := make(chan int)
       ch3 := make(chan int)


       // launch go routines

       wg.Add(3)
       defer wg.Wait()


       go toggle(ch2)
       go toggle(ch3)


       go toggle(ch1)


       for i:=2;i<10;i++ {
              //writing data to channels
              ch1<-i
              ch2<-i
              ch3<-i

              fmt.Println(i)
       }

       //close the channels we need range toggle to return
       close(ch1)
       close(ch2)
       close(ch3)
}

Note: If we are using the wait-group with channels, just remember that every goroutine being waited is exited. So, if you have used range on channels, do close them so that range loop exit.

In the coming sections we will discuss some, concurrency patterns and buffered channels. Till then happy coding.

 

Advertisements

Difference Between Goroutines and Threads

In Golang Concurrency Part I, I said Goroutines are not threads. In this post I will explain the same.

Size

OS threads are basically fixed size stack, preferably 2 MB. It’s a huge space  e.g. invoking 1024 threads will result in 2 GB space occupancy.

A Goroutine starts life with a small stack, typically 2 KB. Because some go routines are too small for a 2 MB stack and stack of Goroutine is growable.

The size limit for a Goroutine stack may be as much as 1GB, so thread is limited for recursive operation because recursive stack greater then 2 MB will cause, stack overflow. Go o the other hand can grow it’s stack to 1 GB, WOW, now huge recursion is possible in Go.

Scheduling

OS threads are scheduled by kernel. Hardware timer dependency.

Go run-time has its own scheduler. No hardware timer dependency. It’s a m:n scheduler. Means, m (Goroutines) => n ( Threads).

 

Identity

Goroutines has no identity, for some it must be an issue, but I can easily live with that. Go has this implemented because Goroutines has  no TLS  (Thread local storage).

Happy coding.

 

Golang Concurrency Part I

Concurrent programming knowledge a necessity these days. Servers need to handle multiple connections and process them simultaniously. Mobile apps are working in a manner that, foreground and backgroung processing is done in saperate context. Since processors are growing in numbers not in speed, we need to design out programs in such a manner.

Go let us use two types of Concurrent Programming:
1. Communicating sequential processes (CSP).
2. Shared memory multi-threaded programming (Traditional).

Goroutines

Goroutines are not threads, but they are like threads. Each concurrently executing activity is called Goroutine. As an example assume a problem in which we are processing multiple types of data and writing in multiple files. So, there are two ways to do that.

  1. Sequential programming.
  2. Concurrent programming.

I will just create an example, and will show you it’s really easy to convert a sequential program to concurrent program in go.

A concurrent file writing program:

Sequential Implementation:

package main

import (
       "os"
       "fmt"
)

var filenamearray []string

func processData(index int) {
       f, _ := os.OpenFile(filenamearray[index],os.O_RDWR | os.O_CREATE,0777) // skipping error
       defer f.Close()
       for i := 0;i<10000000;i++ {
              a := i + index
              fmt.Fprintln(f,a)
       }
}

func main() {

       filenamearray = []string{"a1", "a2", "a3","a4"}

       for i:=0;i<len(filenamearray) ;i++ {
              processData(i)
       }


}

 

Concurrent Implementation:

import (
       "os"
       "fmt"
       "sync"
)

var filenamearray []string

var wg sync.WaitGroup

func processData(index int) {
       f, _ := os.OpenFile(filenamearray[index],os.O_RDWR | os.O_CREATE,0777) // skipping error
       defer wg.Done()
       defer f.Close()

       for i := 0;i<10000000;i++ {
              a := i + index
              fmt.Fprintln(f,a)
       }
}

func main() {

       filenamearray = []string{"a1", "a2", "a3","a4"}

       for i:=0;i<len(filenamearray) ;i++ {
              wg.Add(1)
              go processData(i)
       }

       wg.Wait()

}

When I tried to run both the programs, there was a huge difference in performance:

Sequential took : 1 Minute and 21 seconds approx.

Concurrent took : 28 seconds. 

You can test by changing the number of files.

I the next part I will cover channels, with a practical example. Till then, Happy Coding.

 

 

 

Coin Change (Dynamic Programming)

Hello everyone, just a small tutorial on Coin Change Problem.

Problem:

Given a number of dollars, , and a list of dollar values for distinct coins, , find and print the number of different ways you can make change for dollars if each coin is available in an infinite quantity.

https://www.hackerrank.com/challenges/ctci-coin-change

Solution:

Before coding let’s discuss the problem and solution:

Assume you have unlimited change of { 2, 3, 5, 6}, now you have to tell in how many ways you can make a 10$.

There are many possible ways like, {2,2,2,2,2,} , {2,3,5}.

But how to determine the solution of problem?

There is a recursive solution, in which try all the combinations and if right one is found, increment the count. But doing it recursively is a complex task and the complexity will be O(power(n,m)) and the code is:

package main

import (
       "fmt"
       "sort"
)

var ways int

func coinchange(startIndex int, totalMoney int , coins []int) {
       if startIndex < 0 {
              return
       }
       if totalMoney < 0 {               return        }        if totalMoney == 0 {               ways++               return        }        for i := startIndex;i>=0;i-- {
              coinchange(i,totalMoney-coins[i],coins)
       }

}

func main() {
       var money, numCoins int
       fmt.Scanf("%d%d",&money, &numCoins )
       k := make([]int,numCoins)
       for i:=0;i<numCoins;i++ {
              fmt.Scanf("%d",&k[i] )
       }

       // sort to optimize the calulation
       sort.Ints(k)

       coinchange(numCoins-1,money,k)

       fmt.Println(ways)

}

and this is my output with recursive solution :

Screen Shot 2017-02-18 at 9.15.50 pm.png

The solution is fine and clears few of the test cases, but it gets timeout for the large dataset. The basic problem is while designing our solution we are solving the problems again and again. Like, {6,4} is 10 and {6,2,2}is 10 and {2,2} is 4 and we are recalulating it again and again.

To to solve this we will use Dynamic programming.

package main
import "fmt"

func main() {
       var money, numCoins int
       fmt.Scanf("%d%d",&money, &numCoins )
       k := make([]int,numCoins)
       for i:=0;i<numCoins;i++ {
              fmt.Scanf("%d",&k[i] )
       }
       // make a DP array
       dp := make([]int,money+1)
       dp[0] = 1
       for i:=0;i<numCoins;i++ {
              start := k[i]
              for j:=start;j<=money;j++ {
                     // use the saved solution
                     dp[j] += dp[j-start]
              }
       }
       fmt.Println(dp[money])
}

Screen Shot 2017-02-18 at 9.20.47 pm.png

Our DP Solution clears all the test cases on Hacker  rank.

Explanation:

Now we need a way to save the solution of already solved problems, we will use an array for same.

Screen Shot 2017-02-18 at 9.43.12 pm.png

Map this diagram with code comments and you will figure it out.

Bye everyone, happy coding.

Golang Builder Pattern (Creational)

After a basic explanation of Abstract Pattern in Golang. There is need that, I should explain a more powerful design pattern, which will help in creating more complex objects. The pattern is Builder Pattern.

What is Builder Design Pattern

Design pattern books are boring. You may disagree but it’s my personal feeling. hehehe… But I will try make this part a bit interesting. Every book has example of same food company, even websites explaining design pattern are using same examples again and again.

But I will first user some theoretical terms and then with help of diagrams, I will explain it. Builder pattern comes in to picture when you have complex product. Means a product with may inputs, for e.g. A Car company like Audi, manufactures many kind of cars, although they all are cars but all are different, Audi Q3 , Audo Q4, Audi R8. How they accomplish it in a same factory is an example of Builder Pattern.

In builder pattern we just need to remember five components:

Director: Director performs all the required steps given inside builder to create a product. In our case our production line in our director. It will invoke all the abstract builder steps to create our Audi.

Abstract Builder: Abstract builder provides common interface for concrete builder. All the method inside our abstract builder will be implemented by our concrete Audi builders.

Concrete Builder: There will be multiple concrete builders, one for each kind of Audi.

Product: Audi is our product and based on builder we will decide which Audi it is.

When all the above components work together, it makes a builder pattern. I know it’s not easy to grasp but believe me GO code I will write, will explain you everything.

Untitled.png

The above drawing, just explains, Director consists of an abstract builder and based on input, director will invoke a concrete builder to create out favorite Audi.

Golang Code For Builder Pattern

package main

import "fmt"

//this is Product.
type MyAudi struct {
       name string
       wheelSize string
       engineCapacityCC int
       powerBHP int
       torque int
       fuelType string
       cost int
}

func (m MyAudi) showAudi() {
       fmt.Println("Audi Name : " , m.name)
       fmt.Println("Audi wheel : " , m.wheelSize)
       fmt.Println("Audi Engine : " , m.engineCapacityCC)
       fmt.Println("Audi power bhp : " , m.powerBHP)
       fmt.Println("Audi Torque : " , m.torque)
       fmt.Println("Audi fuel : " , m.fuelType)
       fmt.Println("Audi Cost INR: " , m.cost)

}

//this is abstract builder
type AudiBuilder interface {
       createAudi() MyAudi
}

//now concrete builders
type AudiQ3Builder struct {
}

func (a AudiQ3Builder) createAudi() MyAudi {
       audi := MyAudi{}
       audi.name = "AydiQ3"
       audi.cost = 1000000000
       audi.engineCapacityCC = 3000
       audi.fuelType = "Diesel"
       audi.powerBHP = 300
       audi.torque = 480
       audi.wheelSize = "R17/75/250"
       return audi
}


//now concrete builders
type AudiQ4Builder struct {
}

func (a AudiQ4Builder) createAudi() MyAudi {
       audi := MyAudi{}
       audi.name = "AydiQ4"
       audi.cost = 2000000000
       audi.engineCapacityCC = 4000
       audi.fuelType = "Patrol"
       audi.powerBHP = 400
       audi.torque = 580
       audi.wheelSize = "R19/85/250"
       return audi
}


// you may implement other builder urself :P


//this is director

type ProductionLine struct {
       builder AudiBuilder
}

func (a ProductionLine)CreateMyAudi() MyAudi {
       return a.builder.createAudi()
}

func main() {
       p := ProductionLine{AudiQ3Builder{}}
       res := p.CreateMyAudi()
       res.showAudi()
       fmt.Println("=============================================================================")
       p = ProductionLine{AudiQ4Builder{}}
       res = p.CreateMyAudi()
       res.showAudi()

}

output:

Audi Name : AydiQ3
Audi wheel : R17/75/250
Audi Engine : 3000
Audi power bhp : 300
Audi Torque : 480
Audi fuel : Diesel
Audi Cost INR: 1000000000
=============================================================================
Audi Name : AydiQ4
Audi wheel : R19/85/250
Audi Engine : 4000
Audi power bhp : 400
Audi Torque : 580
Audi fuel : Patrol
Audi Cost INR: 2000000000

Dear friends, I tried to keep the example easy, but this pattern solves way more complex problems then this. Hope this may help you to understand this pattern.

Next in line is a RSA encryption based file transfer program, which will help you to understand, how PKI works basically.

Happy coding. 🙂

 

Golang Cryptography Part II

Hello friends, after Cryptography Part I  back with my first example of crypto. Golang has a package AES. In the further blog, I will write a Client Server application, which runs on the encrypted data. So, ready to share some secret over network. Shhh…..

Client Code

package main

import (
       "net"
       "fmt"
       "crypto/aes"
)

//this example just tests the data length of block size 16

var key = "12345678912345678912345678912345"

func encryptWriteData(conn net.Conn, data []byte) {
       //creating a block cipher
       block, err := aes.NewCipher([]byte(key))
       if err != nil {
              fmt.Println(err.Error())
       }

       fmt.Println(block.BlockSize())
       mydata := make([]byte,16)

       if len(data) > 16 {
              fmt.Println("Max 16 bytes can be sent in this example...")
              return
       }
       //copy bytes because, even if message is less then 16 bytes, we need 16 bytes.
       copy(mydata,data)

       block.Encrypt(mydata,mydata)

       //sending encrypted data
       conn.Write(mydata)
}

func printDecryptedData(conn net.Conn) {
       data := make([]byte,16)

       _,err :=  conn.Read(data)

       if err != nil {
              fmt.Println(err.Error())
       }

       block, err := aes.NewCipher([]byte(key))
       if err != nil {
              fmt.Println(err.Error())
       }

       mydata := make([]byte,16)

       if len(data) > 16 {
              fmt.Println("Max 16 bytes can be sent in this example...")
              return
       }
       //copy bytes because, even if message is less then 16 bytes, we need 16 bytes.

       copy(mydata,data)

       block.Decrypt(mydata,mydata)

       fmt.Println(string(mydata))

}


func main() {

       conn,err := net.Dial("tcp","127.0.0.1:4908")
       if err != nil {
              fmt.Println(err.Error())
              return
       }

       var input int
       for {
              fmt.Scanf("%d",&input)
              switch input {
              case 1:
                     encryptWriteData(conn,[]byte("Hello Server"))
              case 2:
                     encryptWriteData(conn,[]byte("Password"))
              case 3:
                     encryptWriteData(conn,[]byte("1234"))
              case 4:
                     encryptWriteData(conn,[]byte("Quit"))
              default:
                     encryptWriteData(conn,[]byte("Invalid"))
              }
              printDecryptedData(conn)
       }


}

Server Code

package main

import (
       "net"
       "fmt"
       "crypto/aes"
)



var key = "12345678912345678912345678912345"

func encryptWriteData(conn net.Conn, data []byte) {
       //creating a block cipher
       block, err := aes.NewCipher([]byte(key))
       if err != nil {
              fmt.Println(err.Error())
       }

       mydata := make([]byte,16)

       if len(data) > 16 {
              fmt.Println("Max 16 bytes can be sent in this example...")
              return
       }
       //copy bytes because, even if message is less then 16 bytes, we need 16 bytes.

       copy(mydata,data)

       block.Encrypt(mydata,mydata)

       //sending encrypted data
       conn.Write(mydata)
}

func printDecryptedData(conn net.Conn) int {
       data := make([]byte,16)

       _,err :=  conn.Read(data)

       if err != nil {
              fmt.Println(err.Error())
              return -1
       }

       block, err := aes.NewCipher([]byte(key))
       if err != nil {
              fmt.Println(err.Error())
              return -1
       }

       mydata := make([]byte,16)

       if len(data) > 16 {
              fmt.Println("Max 16 bytes can be sent in this example...")
              return -1
       }
       //copy bytes because, even if message is less then 16 bytes, we need 16 bytes.

       copy(mydata,data)

       block.Decrypt(mydata,mydata)

       k := string(mydata)

       fmt.Println(k)


       if k[:4] == "Quit" {
              conn.Close()
              return -1
       }

       encryptWriteData(conn,[]byte("Server Message"))
       return 0


}

func processRequest(conn net.Conn){
       for {
              if -1 == printDecryptedData(conn) {
                     fmt.Println("Connection closed...")
                     return
              }
       }

}


func main() {
       conn,err := net.Listen("tcp","127.0.0.1:4908")

       if err != nil {
              fmt.Println(err.Error())
              return
       }

       fmt.Println("Server started...")


       for  {
              c, err := conn.Accept()
              if err != nil {
                     fmt.Println(err.Error())
                     return
              }
              go processRequest(c)
       }


       a := 1
       fmt.Scanf("%d",&a)
}

 

 

==========================================================================

Our client and server, are connected over a network, in our case its local, you can change IP of course.  That’s how it works:

  • Client send message to server.
  • Server sends a encrypted reply to it.
  • On Client sending Quit, server quits.

Code is commented, soon I will upload it too my Github. Happy Coding.

Golang Cryptography Part I

Hello friends, my job profile deals a lot with security. From last one year I have been working with Microsoft Crypto Providers, Openssl engines and lot’s of stuff. So, I started discovering the same in Golang. So, in this article I will explain the Golang crypto module with examples, and some use cases. Let’s start.

 What is Cryptography

I simple terms, cryptography is a digital technology that secures your data, like passwords, credit card number or anything which you want to secure. It fulfills following four goals.

The four points are linked to Wikipedia pages. To go in details, you can refer same, I will explain them in very short definitions.

Confidentiality is data cannot be read by any other parties.

Data Integrity  is , the crypt operation must not change data.

Authentication is, data must be read by Authenticated party.

Non-repudiation, is the party which is sending the data cannot deny, that they have not sent it.

Some Technical Terms

Cryptography Algorithms

Cryptography algorithms are algorithms which are needed when we do crypt operations, like encryption, decryption, sign and verify. In layman terms, we are locking our data. So, for locking our data we need a key and to unlock it we need the key. So all the cryptography is based on key.

Based on keys, cryptography can be classified in two categories:

  1. Symmetric
  2.  Asymmetric 

Symmetric Cryptography

  • Only one key can encrypt.
  • Same key can decrypt.
  • Both the parties need to hold key.

Asymmetric Cryptography

  • Consists of two keys, PUBLIC and PRIVATE
  • Data encrypted by Private can only be decrypted by Public.
  • data encrypted by Public can only be decrypted by Private.

This was a small description of crypto, now in next parts. I will do a client server example for both.

Crypto in Golang

Golang has a package, Golang Crypto. Which fulfills almost all the application crypto needs.

It Provides implementation of, Symmetric, Asymmetric and Message Digests implimentations.

aes : Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.

cipher:  Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations.

des: Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.

dsa: Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.

ecdsa: Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-3.

elliptic: Package elliptic implements several standard elliptic curves over prime fields.

hmac: Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198.

md5: Package md5 implements the MD5 hash algorithm as defined in RFC 1321.

rand: Package rand implements a cryptographically secure pseudorandom number generator.

rc4: Package rc4 implements RC4 encryption, as defined in Bruce Schneier’s Applied Cryptography.

rsa: Package rsa implements RSA encryption as specified in PKCS#1.

sha1: Package sha1 implements the SHA1 hash algorithm as defined in RFC 3174.

sha256: Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.

sha512: Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.

subtle: Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.

tls: Package tls partially implements TLS 1.2, as specified in RFC 5246.

x509: Package x509 parses X.509-encoded keys and certificates.

pkix: Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.

In coming, pages, I will  discuss most of them in a live example.

Till then, Happy Coding. 🙂

A One Pager Tutorial of Go

Hello programmers, how are you guys. A friend asked me for a crash course on Golang. So, I am making it really short. This post will be helpful for programmers who are new to Go and don’t know where to go in Golang. I will write a basic tutorial with links, so be ready for a fast pace tutorial or a simple crash course.

I will cover the following topics:

  • What is Go (little-little)
  • How to install and configure.
  • Run first go program.
  • Go types and variables and scope
  • Arrays , Slices and Maps
  • If-else and switch
  • Loops
  • Functions and Closures
  • Structure and Interfaces

What is Go

I will say it’s another programming language. I learned it because, being C++ programmer I was in need of a language which is same as C or C++ in terms of performance and helps me to code my small services which runs on network and devlopment is really fast paced . So, I start reading about Go and fell in love with the language. If you need some boogie details of go history visit, gaolang.org, it says, “Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.

How to install and configure

Go to Golang Website and just download it, on windows it is installed in C:\Go and On Mac it goes in /usr/local/go. As a beginer you just need to install and you are ready to run the program.

Note: I downloaded Intelij Idea and installed a plugin for Golang.

GOPATH 

The GOPATH environment variable specifies the location of your workspace. It is likely the only environment variable you’ll need to set when developing Go code.You can use GOPATH once you are able to run simple applications in Golang.

First GO Program

Create a file named, main.go

// go program need a package main
package main

// to use any golang functionality we need to import it.
import "fmt"

func main() {
 // Println is function of fmt package
 fmt.Println("Hello Friends")
}

Run it using, # go run main.go

=============================================
output:
Hello Friends

=============================================

Note: You can also run your programs online @Go Tour.

Go Types and Variables and Scope

Numbers

  • Integers ( uint8, uint16, uint32, uint64, int8, int16, int32 and int64 )
  • Float  : Go has two floating point types: float32 and float64 (also often referred to as single precision and double precision respectively)

Strings

  • “Rajni” , “Friends” are example of Golang string.

Booleans

  • true and false are two states of boolean

Variables

Variables in Golang are same as any other language. But their way of representation is different. They are declared as follows:

var variableName variableType

e.g. Lets write code.

package main

import "fmt"

func main() {
    // declare a variable and assign
    var myInt int = 10
    
    //auto type deduction using :=
    myInt2 := 20

    var myStr string = "Hello"

    myStr2:= "World"

    fmt.Println(myInt + myInt2)
    //string addition works in Golang
    fmt.Println(myStr + myStr2)
}

output:
30
Hello World

Variable Scope

package main 

import "fmt" 

//global variable scope 
var x string = "Hello World Global" 

func main() 
{ 
    fmt.Println(x) f() 
} 

func f() 
{ 
    // local variable scope 
    var x string = "Hello World Local" 
    fmt.Println(x) 
}


Arrays and Slices

var a [4]int //an array of integers size 4
b := [2]string{"Penn", "Teller"} // string array

Array are same as other programming language arrays, but the the way to declare them is a bit different. Lets do an example:

package main

import "fmt"


func main(){
       //array example
       var intarray [4]int
       intarray[0] = 1
       intarray[1] = 2
       intarray[2] = 3
       intarray[3] = 4
       fmt.Println(intarray)

       b := [2]string{"test1", "test2"}
       fmt.Println(b)
       b[0] = "new_test"
       fmt.Println(b)
}

Output:

[1 2 3 4]
[test1 test2]
[new_test test2]

Slices Example

package main

import "fmt"


func main(){
 //array example
 var intarray [4]int
 intarray[0] = 1
 intarray[1] = 2
 intarray[2] = 3
 intarray[3] = 4
 fmt.Println(intarray)

 //example of a slice, we sliced array from 1 to 3 
 b := intarray[1:3]
 fmt.Println(b)

}

Maps In Golang

They are also known as dictionaries, a sample code to use them, :

package main

import "fmt"


func main(){

       a := make(map[string]string)
       a["Myname"] = "Rajni"
       a["MyJob"] = "No Job"

       fmt.Println(a)
       fmt.Println(a["Myname"])
       fmt.Println(a["MyJob"])
       //check non existent
       fmt.Println(a["Noval"])

}

If-else

// Branching with `if` and `else` in Go is
// straight-forward.

package main

import "fmt"

func main() {

       // Here's a basic example.
       if 7%2 == 0 {
              fmt.Println("7 is even")
       } else {
              fmt.Println("7 is odd")
       }

       // You can have an `if` statement without an else.
       if 8%4 == 0 {
              fmt.Println("8 is divisible by 4")
       }

       // A statement can precede conditionals; any variables
       // declared in this statement are available in all
       // branches.
       if num := 9; num < 0 {
              fmt.Println(num, "is negative")
       } else if num < 10 {
              fmt.Println(num, "has 1 digit")
       } else {
              fmt.Println(num, "has multiple digits")
       }

       name := "rajni"

       if name == "rajni" {
              fmt.Println("Hi Rajni")
       } else {
              fmt.Println("Bye Rajni")
       }
}

output:
7 is odd
8 is divisible by 4
9 has 1 digit
Hi Rajni

 

Switch-Case

// _Switch statements_ express conditionals across many
// branches.

package main

import "fmt"
import "time"

func main() {

       // Here's a basic `switch`.
       i := 2
       fmt.Print("Write ", i, " as ")
       switch i {
       case 1:
              fmt.Println("one")
       case 2:
              fmt.Println("two")
       case 3:
              fmt.Println("three")
       }


       switch time.Now().Weekday() {
       
       case time.Saturday, time.Sunday:
              fmt.Println("It's the weekend")
       default:
              fmt.Println("It's a weekday")
       }

       // `switch` without an expression is an alternate way
       // to express if/else logic. Here we also show how the
       // `case` expressions can be non-constants.
       t := time.Now()
       switch {
       case t.Hour() < 12:
              fmt.Println("It's before noon")
       default:
              fmt.Println("It's after noon")
       }

       // A type `switch` compares types instead of values.  You
       // can use this to discover the the type of an interface
       // value.  In this example, the variable `t` will have the
       // type corresponding to its clause.
       whatAmI := func(i interface{}) {
              switch t := i.(type) {
              case bool:
                     fmt.Println("I'm a bool")
              case int:
                     fmt.Println("I'm an int")
              default:
                     fmt.Printf("Don't know type %T\n", t)
              }
       }
       whatAmI(true)
       whatAmI(1)
       whatAmI("hey")
}

Loops

// `for` is Go's only looping construct. Here are
// three basic types of `for` loops.

package main

import "fmt"

func main() {

       // The most basic type, with a single condition.
       i := 1
       for i <= 3 {
              fmt.Println(i)
              i = i + 1
       }

       // A classic initial/condition/after `for` loop.
       for j := 7; j <= 9; j++ {
              fmt.Println(j)
       }

       // `for` without a condition will loop repeatedly
       // until you `break` out of the loop or `return` from
       // the enclosing function.
       for {
              fmt.Println("loop")
              break
       }

       // You can also `continue` to the next iteration of
       // the loop.
       for n := 0; n <= 5; n++ {
              if n%2 == 0 {
                     continue
              }
              fmt.Println(n)
       }
}

 

Functions

// _Functions_ are central in Go. We'll learn about
// functions with a few different examples.

package main

import "fmt"

// Here's a function that takes two `int`s and returns
// their sum as an `int`.
func plus(a int, b int) int {

       // Go requires explicit returns, i.e. it won't
       // automatically return the value of the last
       // expression.
       return a + b
}

// When you have multiple consecutive parameters of
// the same type, you may omit the type name for the
// like-typed parameters up to the final parameter that
// declares the type.
func plusPlus(a, b, c int) int {
       return a + b + c
}

func main() {

       // Call a function just as you'd expect, with
       // `name(args)`.
       res := plus(1, 2)
       fmt.Println("1+2 =", res)

       res = plusPlus(1, 2, 3)
       fmt.Println("1+2+3 =", res)
}

 

Closures

Closures are like lambdas, in some languages.

// Anonymous functions are useful when you want to define
// a function inline without having to name it.

package main

import "fmt"

// This function `intSeq` returns another function, which
// we define anonymously in the body of `intSeq`. The
// returned function _closes over_ the variable `i` to
// form a closure.
func intSeq() func() int {
       i := 0
       return func() int {
              i += 1
              return i
       }
}

func main() {

       // We call `intSeq`, assigning the result (a function)
       // to `nextInt`. This function value captures its
       // own `i` value, which will be updated each time
       // we call `nextInt`.
       nextInt := intSeq()

       // See the effect of the closure by calling `nextInt`
       // a few times.
      //state of nect int is saved
       fmt.Println(nextInt())
       fmt.Println(nextInt())
       fmt.Println(nextInt())

       // To confirm that the state is unique to that
       // particular function, create and test a new one.
       newInts := intSeq()
       fmt.Println(newInts())
}

 

Struct in Golang

// Go's _structs_ are typed collections of fields.
// They're useful for grouping data together to form
// records.

package main

import "fmt"

// This `person` struct type has `name` and `age` fields.
type person struct {
       name string
       age  int
}

func main() {

       // This syntax creates a new struct.
       fmt.Println(person{"Bob", 20})

       // You can name the fields when initializing a struct.
       fmt.Println(person{name: "Alice", age: 30})

       // Omitted fields will be zero-valued.
       fmt.Println(person{name: "Fred"})

       // An `&` prefix yields a pointer to the struct.
       fmt.Println(&person{name: "Ann", age: 40})

       // Access struct fields with a dot.
       s := person{name: "Sean", age: 50}
       fmt.Println(s.name)

       // You can also use dots with struct pointers - the
       // pointers are automatically dereferenced.
       sp := &s
       fmt.Println(sp.age)

       // Structs are mutable.
       sp.age = 51
       fmt.Println(sp.age)
}

Method

// Go supports _methods_ defined on struct types.

package main

import "fmt"

type rect struct {
       width, height int
}

// This `area` method has a _receiver type_ of `*rect`.
func (r *rect) area() int {
       return r.width * r.height
}

// Methods can be defined for either pointer or value
// receiver types. Here's an example of a value receiver.
func (r rect) perim() int {
       return 2*r.width + 2*r.height
}

func main() {
       r := rect{width: 10, height: 5}

       // Here we call the 2 methods defined for our struct.
       fmt.Println("area: ", r.area())
       fmt.Println("perim:", r.perim())

       // Go automatically handles conversion between values
       // and pointers for method calls. You may want to use
       // a pointer receiver type to avoid copying on method
       // calls or to allow the method to mutate the
       // receiving struct.
       rp := &r
       fmt.Println("area: ", rp.area())
       fmt.Println("perim:", rp.perim())
}

Interfaces

// _Interfaces_ are named collections of method
// signatures.

package main

import "fmt"
import "math"

// Here's a basic interface for geometric shapes.
type geometry interface {
       area() float64
       perim() float64
}

// For our example we'll implement this interface on
// `rect` and `circle` types.
type rect struct {
       width, height float64
}
type circle struct {
       radius float64
}

// To implement an interface in Go, we just need to
// implement all the methods in the interface. Here we
// implement `geometry` on `rect`s.
func (r rect) area() float64 {
       return r.width * r.height
}
func (r rect) perim() float64 {
       return 2*r.width + 2*r.height
}

// The implementation for `circle`s.
func (c circle) area() float64 {
       return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
       return 2 * math.Pi * c.radius
}

// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic `measure` function taking advantage of this
// to work on any `geometry`.
func measure(g geometry) {
       fmt.Println(g)
       fmt.Println(g.area())
       fmt.Println(g.perim())
}

func main() {
       r := rect{width: 3, height: 4}
       c := circle{radius: 5}

       // The `circle` and `rect` struct types both
       // implement the `geometry` interface so we can use
       // instances of
       // these structs as arguments to `measure`.
       measure(r)
       measure(c)
}

 

These are some basic Golang codes, I just copied the examples and pointed to the link. This part if strictly for coders, who can program and a Golang refresher.

See you soon. Happy Coding.

 

 

Golang Design Pattern Abstract Factory and Factory Method

Hello my dear friends. This post will discuss a Creational design pattern Abstract Factory and we will implement it in Golang. There are too many complex definition of Abstract Factory written by very very wide people, but I call my self a normal guy, who just understand the basic language. I will try to explain it in a same way and will implement in Golang.

type AbstractFactory interface {
        CreateMyLove()
}

AbstractFactory is a interface which provides a method CreateMyLove(). This a basic thing we need for Abstract Factory.

CreateMyLove() is a factory method.

To explain this all, I will just say without knowing the concrete objects our AbstractFactory can create an objects of my GirlFriend. Now I am ready to create my concrete girlfriend.

package main

import "fmt"

// this is my concrete girl friend
type GirlFriend struct {
       nationality string
       eyesColor string
       language string
}

// abstract factory for creating girlfriend
type AbstractFactory interface {
        CreateMyLove() GirlFriend
}


// my indian girlfriend
type IndianGirlFriendFactory struct {

}

// mu korean girlfirend
type KoreanGirlFriendFactory struct {

}

// concrete implementation
func (a IndianGirlFriendFactory) CreateMyLove() GirlFriend {
       return GirlFriend{"Indian" , "Black" , "Hindi"}
}


// concrete implementation
func (a KoreanGirlFriendFactory) CreateMyLove() GirlFriend {
       return GirlFriend{"Korean" , "Brown" , "Korean"}
}


// main factory method
func getGirlFriend(typeGf string) GirlFriend {

       var gffact AbstractFactory
       switch typeGf {
       case "Indian":
              gffact = IndianGirlFriendFactory{}
              return gffact.CreateMyLove()
       case "Korean":
              gffact = KoreanGirlFriendFactory{}
              return gffact.CreateMyLove()
       }
       return GirlFriend{}
}

func main(){

       var typeGf string
       fmt.Scanf("%s", &typeGf)
       a := getGirlFriend(typeGf)

       fmt.Println(a.eyesColor)

}

Above is a basic implementation for Abstract Factory in Golang. If you need more details Wikipedia is a great place to refer for design patterns understanding. You don’t need to use them every-time. Just use them when you need them most, because they make code reusable but, their implementation is complex. See you soon friends.  🙂

Playing with Reflections in Golang

What Are Reflections in Programming?

I went through many articles e.g. Wiki and Quora. These are very nice articles, but what I miss is essence of simplicity for a newbie programmer. So, I will try to explain this in really simple words and we will experiment with  Golang.

Let’s go point by point:

  • Reflection can help you to identify the type of an object at run time.
  • Yes, type can be printed as string.
  • Reflection can create an object from string. It means if I give you a configuration file with class names, you can configure your designs with that file by creating objects based on names.

A basic example of reflection, is finding function name from a windows DLL (GetProcAddress). This function helps us to find the function address from it’s name and we can call that address to execute that function.

// declare a type PGNSI
typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);

//declare a variable of type PGNSI
   PGNSI pGNSI;
   SYSTEM_INFO si;

   
   // get address of funtion GetNativeSystemInfo and store in pGNSI
   pGNSI = (PGNSI) GetProcAddress(handle, "GetNativeSystemInfo");
   if(NULL != pGNSI)
   {
      // call function
      pGNSI(&si);
   }

don’t get confused above code in in C language just don’t try to run it, it’s just for explanation of concept.

Reflections in Golang

Golang also implements this beautiful feature of reflection. There is a sweet blog , Laws Of Reflection.

Type and Interface in Golang

Before diving into reflections, we need a little backgroung on types and interfaces. “Go is a statically typed language“, yes one type cannot be automatically typed in to another.

e.g.

package main
import "fmt"

func main() {

       type MyInt int
       var a int = 0
       var b MyInt = 10

       fmt.Println("Before")
       fmt.Println(a)
       fmt.Println(b)

       //a = b // .\main.go:18: cannot use b (type MyInt) as type int in assignment
       a = int(b) // good assignment

       fmt.Println("After")
       fmt.Println(a)
       fmt.Println(b)
}

Although MyInt and int are same kind of type, but we cannot assign one to another.

Interfaces in Go 

Interfaces are special kind of type, e.g.

// Reader is the interface that wraps the basic Read method.
type Reader interface {
       Read(p []byte) (n int, err error)
}

// Writer is the interface that wraps the basic Write method.
type Writer interface {
       Write(p []byte) (n int, err error)
}

//an empty interface
type EmptyIface interface {

}
  • Every type in Golang implements empty interface.
  • A non empty interface consists of rule or method, any type abiding that rule becomes of interface type. e.g.
package main
import "fmt"

// Reader is the interface that wraps the basic Read method.
type Reader interface {
       Read(p []byte) (n int, err error)
}


type MyInt int

// MyInt implements Reader interface
func (a MyInt) Read(p []byte) (n int, err error) {
       return 10 ,nil
}

func main() {

       var b MyInt = 10

       p,_ := b.Read(nil)

       fmt.Println(p)

}

We don’t need type assertions for empty interface.

package main
import "fmt"


type Empty interface {

}

func main() {
       var data empty = 10
       fmt.Println(data)
}

As we are clear with types and interfaces let’s begin reflections.

Reflections

Go implements it’s reflection functionality in Package Reflection. The package consists of many routines and types let’s learn by using it.

reflect.TypeOf()

reflect.TypeOf() return a Type variable, which represents a Go Type. We can see this in output of the code below.

package main
import "fmt"
import "reflect"

type TestStruct struct {
       test int
}


type Inface interface {
       read()
}
func (k TestStruct) read() {

}

func main() {

       var integer int = 10
       var structure TestStruct
       var interfaceblank Inface
       var interfacew Inface  = TestStruct{}
       var interfacep Inface  = &TestStruct{}
       var myarray [6]int

       fmt.Println("=============================================================")
       var test reflect.Type =  reflect.TypeOf(integer)
       fmt.Println("output integer: ",test)
       fmt.Println("output integer kind: ",test.Kind())
       fmt.Println("=============================================================")


       test = reflect.TypeOf(structure)
       fmt.Println("output structure: ",test)
       fmt.Println("output structure kind: ",test.Kind())
       fmt.Println("=============================================================")

       test = reflect.TypeOf(interfaceblank)
       fmt.Println("output interfaceblank: ",test)
       //fmt.Println("output integer kind: ",test.Kind()) // panics for nil interface
       fmt.Println("=============================================================")

       test = reflect.TypeOf(interfacew)
       fmt.Println("output interfacew: ",test)
       fmt.Println("output interfacew kind: ",test.Kind())
       fmt.Println("=============================================================")

       test = reflect.TypeOf(interfacep)
       fmt.Println("output interfacep: ",test)
       fmt.Println("output interfacep kind: ",test.Kind())

       test = reflect.TypeOf(myarray)
       fmt.Println("output myarray: ",test)
       fmt.Println("output myarray kind: ",test.Kind())
       fmt.Println("output myarray elem: ",test.Elem())
}

=============================================================
output integer: int
output integer kind: int
=============================================================
output structure: main.TestStruct
output structure kind: struct
=============================================================
output interfaceblank: 
=============================================================
output interfacew: main.TestStruct
output interfacew kind: struct
=============================================================
output interfacep: *main.TestStruct
output interfacep kind: ptr
=============================================================
output myarray: [6]int
output myarray kind: array
output myarray elem: int

Type is the representation of a Go type.

A Kind represents the specific kind of type that a Type represents. The zero Kind is not a valid kind.

An Elem() will give type of element inside a Type. It panics if  type’s kind is not array, slice, channel, map or pointer.

Reflection A Live Code Example

 

package main

import (

       "fmt"

       "reflect"

)

type MyStruct struct {

       Name string `tag_name:"Name"`

       Wife  string `tag_name:"Wife"`

       Age       int    `tag_name:"Age"`

}

func (f * MyStruct) reflectIt() {

       // take out type inside *f

       val := reflect.ValueOf(f).Elem()

       // iterate over all the fields inside structure

       for i := 0; i < val.NumField(); i++ {
// read value of field

valueField := val.Field(i)

//read type of field

typeField := val.Type().Field(i)

// read tag of field

tag := typeField.Tag

fmt.Printf("Field Name: %s,\t Field Value: %v,\t Tag Value: %s\n", typeField.Name, valueField.Interface(), tag.Get("tag_name"))

}

}

func main() {

f := &MyStruct{Name: "Rajni",Wife:"Sakshi",Age:30,}

f.reflectIt()

}

output:
==============================================================================
Field Name: Name, Field Value: Rajni, Tag Value: Name
Field Name: Wife, Field Value: Sakshi, Tag Value: Wife
Field Name: Age, Field Value: 30, Tag Value: Age

The code above explains the reflection in few lines. Will be back with more topics. See you soon.

Happy Coding.