Friday, November 16, 2018

Learn Golang Tutorials - File Directory IO operations Guide with examples

Golang File Operations

In Any programming language, File IO operations are basic functionality.  These operations are low-level calls made to underline operating System to operate physical files.
Go Language also provides many operations as part of standard packages. All these operations accept input, process it and output to or from physical files.

There are many standard inbuilt packages that we are going to use in this post
  • bufio package  It contains functions
  • IOUtil package  has functions for Input and Output operations
  • os package provides platform independent functionalities for Operating System.
Here are important notes of a File in any programming language
  • A file is a  collection of data stored under a computer machine.
  • Each file contains the name and path of the file 
  • Filename contains the actual name of the file suffixed with the file extension. The extension is a type the file.
  • The path is a  file location in the underline operation System file system. The path can be the absolute or relative path
  • The absolute path is a path from the Root folder to file location. This is specific to Operating System.
  • A relative path is a path which is relevant from the current directory.
  • In Operation System, Filename is unique in Directory.

Examples

Following are the basic examples that you need to know when you are dealing with go language files.

Empty File Creation

This is a simple and easy example of creating an empty file.
In the below example, Standard os package provides create a function. 
Syntax is Create(path) (*File, error)
It accepts path. the path can be an absolute path or relative path. This creates  a physical named file if already exits the same name, truncate it 
This file returns two parameters, First, one is returned file reference to this file for IO operations. second is an error if any exists on creating a file.
The file is created with default permission mask 0666
package main
import (
 "log"
 "os"
)
func main() {
 emptyFile, error := os.Create("EmptyFile.txt")
 if error != nil {
  log.Fatal(error)
 }
 log.Println(emptyFile)
 emptyFile.Close()
}
a log is a standard inbuilt in basic logging package. And function Fatal is equal to Println+ os.exit.

Copy a files

Copy of files will transfer the file and its content from source to destination
If you want to implement copy functionality, Following things need to be done
  • Open a source file for reading using os.open() function
  • Read the content of a file using in memory or  buffer, In
  • Create a new file in the target directory with the same name using os.OpenFile with O_RDWR|os.O_CREATE for Create, Read and Write permissions
  • Write the source file content to target file using io.copy() method
  • Finally close source and target files using defer reader/writer.close()
Following is an example of copying a file
import (
 "io"
 "log"
 "os"
)

func main() {
 source, sourceError := os.Open("source.txt")
 if sourceError != nil {
  log.Fatal(sourceError)
 }
 defer source.Close()

 target, targetError := os.OpenFile("target.txt", os.O_RDWR|os.O_CREATE, 0666)
 if targetError != nil {
  log.Fatal(targetError)
 }
 defer target.Close()
 _, copyError := io.Copy(target, source)
 if copyError != nil {
  log.Fatal(copyError)
 }
}
and the result is source.txt file is copied to target.txt

File metadata information - Name,size,permissions, Date information 

package Os function Stat() returns FileInfo object.FileInfo contains metadata information of a file. It contains the name of the file, Size of a file in bytes, File Permissions, Last Modified date and time, file type -directory|file, System process information Sys() is an interface which gives underlying System process information
package main
import (
 "log"
 "os"
)

func main() {
 var file os.FileInfo
 file, error := os.Stat("testfile.txt")
 if error != nil {
  log.Fatal(error)
 }
 log.Println("Name of the File:", file.Name())
 log.Println("Size of File:", file.Size())
 log.Println("Permissions File:", file.Mode())
 log.Println("Last Modified of File:", file.ModTime())
 log.Println("Directory check: ", file.IsDir())
 log.Printf("System Process info: %+v\n\n", file.Sys())
}
An output of the above code is
2018/11/16 12:30:33 Name of the File: testfile.txt
2018/11/16 12:30:33 Size of File: 17
2018/11/16 12:30:33 Permissions File: -rw-rw-rw-
2018/11/16 12:30:33 Last Modified of File: 2018-11-16 12:11:10.3375944 +0530 IST
2018/11/16 12:30:33 Directory check:  false
2018/11/16 12:30:33 System Process info: &{FileAttributes:32 CreationTime:{LowDateTime:200182414 HighDateTime:30702958} LastAccessTime:{LowDateTime:200182414 HighDateTime:30702958} LastWriteTime:{LowD
High:0 FileSizeLow:17}

Rename or move a file name to new name

This is useful when you want to rename a file or move a file from one location to other location. without rename functionality, We need to delete the file and create a file with a new name. The syntax is os.Rename(oldpath,newpath) Rename function accepts oldpath and newpath. It returns an error if any error exists.
import (
 "log"
 "os"
)

func main() {
 Filename := "testfile.txt"
 NewFileName := "testing.txt"
 error := os.Rename(Filename, NewFileName)
 if error != nil {
  log.Fatal(error)
 }
}
The output of the above program is nothing, Buth the testfile.txt is renamed to testing.txt 
In the above program Filename and NewFileName are a path including file names. If it is in a different directory, Output of rename command outputs to a new location with renamed file.

Delete a file 

It is very simple to delete a file from a file system. Inbuilt OS package provides Remove function Syntax is fs.Remove(path) path is the name of the file or directory. Directory always starts with /.
import (
 "log"
 "os"
)

func main() {
 err := os.Remove("testing.txt")
 if err != nil {
  log.Fatal(err)
 }
}
The output is testing.txt file will be removed from the current directory. if any error occurs, It returns Error To delete files from a directory, Iterate all the files in the directory and apply os.Remove() function.

truncate - Reduce file size 

function truncate  reduce file size by specified bytes.
The syntax is os.Truncate(path, bytes) 
the path is the name of the file including the absolute or relative path.
a second parameter is a number of reduced bytes of a file size if the name of the file in the path not exists, It creates an empty file with this. In the below code, If filename.txt is 1024 bytes in size, It truncates the file size to 200 if the size of filename.txt content is less than 200, It keeps its original size if the second parameter is zero, It removes content from the file and makes an empty file
package main
import (
 "log"
 "os"
)
 
func main() {
 err := os.Truncate("filename.txt", 200)
 
 if err != nil {
  log.Fatal(err)
 }
}

check if a File exists 

When we are doing any operations on files, the First requirement checks is to check file exists or not. Standard os package provides Stat() function to get File meta information, If file not exists, Returns an error. The error can be of different errors, We need to check whether these errors are related to file or directories exists IsNotExist() function returns true if the error is related to not exists.
import (
 "log"
 "os"
)

func main() {
 _, err := os.Stat("testfile.txt")
 if err == nil {
  log.Fatal(err)
 }
 if os.IsNotExist(err) {
  log.Fatal("Not Exists")
 }
}

Open and close files 

For reading /writing a file, First We need to open the file. Standard package os provides functions to open a file for reading or write a content. There are two ways we can do it Synta ix
os.Open(filename String) (*File, error) 
Parameters accepted is a name of the file with type string. Which opens a file for reading and default file descriptor O_RDONLY Returns multiple parameters - *File and error- return *File and error null,if file is successfully opened, if error, returns *PathError Here is the example code for opening
file, err := os.Open("filename.txt")
 if err != nil {
  log.Fatal(err)
 }
if the file opens throws error at runtime, The error is open First.go: no such file or directory
func OpenFile(filename string, flag int, perm FileMode) (*File, error)
The parameters are
filename is the name of the file
The flag is of type int which contains the following constant values. This will tell the purpose of the file to do operations.

  • os.O_RDONLY - For Reading only
  • os.O_WRONLY - Write only
  • os.O_RDWR - both Read and write
  • os.O_APPEND Concatenate at end of file
  • os.O_CREATE - Create a file if not exist
  • os.O_TRUNC -Truncate file to reduce the size
We can supply single parameter os.O_RDONLY or multiple parameters separated by | ie os.O_CREATE |os.O_RDWR last parameter is permissions which is of type FileMode Here is the example code for an opening file with various options. the program is to open the file filename.txt for appending the content to end of the file with permissions - 0777
file, err := os.OpenFile("filename.txt",os.O_APPEND, 0777)
 if err != nil {
  log.Fatal(err)
 }
File closing 
when you are dealing with a file, You are doing input and output operations hardware disk. It is an expensive operation in terms of performance. It is always advisable to close the file once done. we can use simple close or can be combined with defer keyword to close file before returning data in a function
file.close() // simple closing  
or 
defer file.close() // this will be closed before returning data from a function

Append content to end of a File 

First Open the file with OpenFile with various options, Here used OpenFile function with O_APPEND to open a file for appending String content once the file is opened, Append data to a file using WriteString of a file. This will create a file if not exist and append the string Close the file once done
import (
 "log"
 "os"
)

func main() {
 file, error := os.OpenFile("employee.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0777)
 if error != nil {
  log.Fatal(error)
 }
 _, error1 := file.WriteString("1 Kiran 2000\n")
 if error1 != nil {
  log.Fatal(error1)
 }
 if error := file.Close(); error != nil {
  log.Fatal(error)
 }

}
The output of the above program is an employee.log file not exist before, a new file is created with below content 1 Kiran 2000

Write to a file

 It is a basic operation to write a content into a file. ioutil package provides WriteFile function which accepts filename, string content in bytes, permissions.
import (
 "io/ioutil"
 "log"
)

func main() {
 strBytes := []byte("Hi,\nWelcome to Go Tutorials\n")
 err := ioutil.WriteFile("samplefile.txt", strBytes, 0666)
 if err != nil {
  log.Fatal(err)
 }

}
The output is the samplefile.txt file is created and content is as follows
Hi,
Welcome to Go Tutorials

File read line by line

 Normally, reading file transfer content to in-memory. bufio package scanner functions provide for the reading line at a time here is samplefile.txt content
Hi,
Welcome to Go Tutorials
Here is a sequence of steps

  • open a file using os.open() function 
  • Create scanner on file reader using bufio.NewScanner() function 
  • read line by line using a scanner.Scan(). scan function read a line at a time

import (
 "bufio"
 "fmt"
 "log"
 "os"
)

func main() {
 fileReader, error := os.Open("samplefile.txt")
 if error != nil {
  log.Fatal(error)
 }
 defer fileReader.Close()

 scanner := bufio.NewScanner(fileReader)
 for scanner.Scan() {
  fmt.Println(scanner.Text())
 }
 error1 := scanner.Err()
 if error1 != nil {
  log.Fatal(error1)
 }
}
Outputs file content line by line into the console.

Golang Directory Operations 

Directory alias is a folder which contains various types of files and nested directories. This will be helpful to organize the files and directory in the Operating System.
Following are various directory input-output operations.

Create a directory if not exists 

we have to use standard package os to create director or folder First os.Stat() method checks meta information of a file or directory, if already exists it returns an error as nil value, do nothing Once the check is completed, we have to call os.MkdirAll(path, permission) to create a directory with given permissions. MkdirAll is like mkdir command in Unix.
func main() {
 _, error := os.Stat("directory")
 if error == nil {
  log.Fatal(error)
 }
 if os.IsNotExist(error) {
  errorDir := os.MkdirAll("directory", 0755)
  if errorDir != nil {
   log.Fatal(error)
  }

 }
}
Outputs the directory is created in the current folder.
Creation of simple directory works as expected when there are nested directories, like directory\\dir2 code also works in windows, but not on other platforms Operating System. The reason is path contains \\ which will not work in UNIX Operation System. The above code is not feasible for platform dependent and nested directory creation.

Creating Nested directories 

if we want to create a nested directory like dir1/dir2 in a current directory, we have to use os.MkdirAll with path and permissions. Path object needs to be created using path/filepath package. Join function in filepath joins all the pats into a single path. It also picks right separator based on the platform
import (
 "log"
 "os"
 "path/filepath"
)

func main() {
 var nestedDir = "kiran/kiran2"
 path := filepath.Join(".", nestedDir)
 error := os.MkdirAll(path, 0777)
 if error != nil {
  log.Fatal(error)
 }

}
The output is Create a directory dir2 under dir1.

List files from a directory

It is a common requirement to list out files and directories of a current directory. package ioutil ReadDir function returns a list of files in sorted order
import (
 "fmt"
 "io/ioutil"
 "log"
)

func main() {
 files, error := ioutil.ReadDir(".")
 if error != nil {
  log.Fatal(error)
 }
 for _, file := range files {
  fmt.Println(file.Name())
 }

}
Output is
EmptyFile.go
EmptyFile.txt
FileInfo.properties

Current working directory print to console

package os provides GetWd() function returns the working director starting from root directory to the current directory
import (
 "fmt"
 "log"
 "os"
)

func main() {
 currentWorkingDirectory, error := os.Getwd()
 if error != nil {
  log.Fatal(error)
 }
 fmt.Println(currentWorkingDirectory)
}
Output returns current working directory absolute path

walk files and directories 

The directory contains files and subdirectory tree. Sometimes It is required to visit each file and subdirectories of the directory. filepath.Walk function is being used here. It accepts directory and custom visit function parameters.
In the below program, Created an anonymous function that is passed Walk function which iterates each file and directory in the directory tree.
import (
 "fmt"
 "log"
 "os"
 "path/filepath"
)

func main() {
 directory := "."
 customVisit := func(path string, fileInfo os.FileInfo, err1 error) error {
  if err1 != nil {
   return err1
  }
  fmt.Println(path, fileInfo.Size())
  return nil
 }
 error := filepath.Walk(directory, customVisit)
 if error != nil {
  log.Println(error)
 }

}
Output is listing out all files and subdirectories recursively to console

Wednesday, November 14, 2018

Learn Golang Tutorials - Beginner guide to Functions with examples

Learn Golang Tutorials - Beginner guide to Functions with examples

Golang Functions

This article covers the following things related to functions in  Go language 
  • why Function are required?
  • Function Declarations
  • Multiple return values
  • Named return values
  • Defer
  • closure
  • Anonymous functions
  • The function assigned as the value
  • passing arguments to the function
  • function slice to an array

why Function is required?

Functions are a program or multiple lines code written to achieve specific functionality. every functionality is defined as a function in Go Langauge.
Every Runnable code in golang has main() function.k The functions can be called by some other code at a different location. The advantages with functions are duplicate code and maintenance of code.
Few key points of a function in golang.
  • Functions are code statements designed to achieve some tasks 
  •  It takes input and executes the code and returns the output
  •  Functions executed  when functions are called by some other code
  •  functions are also called subprograms, methods, procedures
The syntax for defining functions
func functionname([argument1 datatype,argument2 datatype])[returnvaluename returntype]{
code block statement(s)
}
To design functions in any programming language, Following things are required
  • Function Header 
  • Function Body 
  • Function Caller
Function declaration contains header and body.
Few notes about the syntax of the function.
  • func keyword - func is a keyword in golang. Every function declaration always starts with this keyword.
  • functionname - It is function name which is being used to execute by the caller in other location code base 
  • argument1 -  These also called parameter, which will be enclosed with ( and ). The syntax for argument declaration is the argument name followed by data type. Multiple parameters can also be declared separated by a comma. These are optional ie empty parameters also valid.
  • return type - Function return multiple values. declaration of return type contains name and type. Type is optional. Any number of return types can be declared. It is an optional type.
  • Function body - It is actual code written to achieve some tasks which is placed between { and }
  • Function caller - Once the function is declared,  we need to execute a function by calling it. Once the function is called, control goes to function body  and executes it and return the value, once done, control transfer to caller code

Example

We will see various features of functions with various and examples in below sections.

Empty Function declaration

The following is an empty function which has no input parameters and it is not returning anything. This is also a valid function.
func printmessage() {  
 fmt.Println("Hello world")
}
Basic Function with input and output here is an example for function The below function has two input parameters - value1 and value2 of data type int. The return type is also int which returns the sum of these two numbers.
package main

import "fmt"

func sum(value1 int, value2 int) int {
 return value1 + value2
}
func main() {
 fmt.Println(sum(1, 2))

}
We have declared a function. Now we have to call the function. the function is called with function name by giving function parameters. the syntax is sum(1, 2) and the output of the above program is
3
Multiple parameters of the same type 
when there are multiple parameters of the same type are declared side by side, We can avoid by declaring type multiple times with simple syntax as follows
func sum(value1, value2 int) int {
 return value1 + value2
}

Return Multiple values from a functions 

In Other programming languages like Java and javascript always returns a single value. Functions in Golang returns multiple values. Declared IncrementAndDecrement  function with two parameters of the same type, first parameters is incremented by one, the Second parameter is decremented by 1. finally both return the values. if function is returning multiple values, return types must be declared with ( and ). return types in header and body are separated by the comma
func IncrementAndDecrement(value1, value2 int) (int, int) {
 var incrValue = value1 + 1
 var decrValue = value2 - 1
 return incrValue, decrValue
}
func main() {
 value1, value2 := IncrementAndDecrement(5, 5)
 fmt.Printf("%d  %d", value1, value2)
}
The output of the above program code is
6 4
 
Please have a look of below code where return types are not declared in ( and ). It gives compilation error missing function body, unexpected comma after the top-level declaration,non-declaration statement outside the function body
func IncrementAndDecrement(value1, value2 int) int, int {
 var incrValue = value1 + 1
 var decrValue = value2 - 1
 return incrValue, decrValue
}
func main() {
 value1, value2 := IncrementAndDecrement(5, 5)
 fmt.Printf("%d  %d", value1, value2)
}
The complete error report is
A:\Golang\work>go run First.go
# command-line-arguments
.\First.go:5:6: missing function body
.\First.go:5:51: syntax error: unexpected comma after top level declaration
.\First.go:8:2: syntax error: non-declaration statement outside function body

Blank Identifier - subset return values

We already saw multiple return values support in golang. the function is returning two values, the caller has to get the only a subset of data ie one value should be returned from the function. Then we will use the blank identifier for this. _ is called as a blank identifier. on which any type of value accepts and not returned from function The IncrementAndDecrement function returns two values, But the caller needs only one value, Another value place should be replaced with a blank identifier (_)
package main

import "fmt"

func IncrementAndDecrement(value1, value2 int) (int, int) {
 var incrValue = value1 + 1
 var decrValue = value2 - 1
 return incrValue, decrValue
}
func main() {
 _, value2 := IncrementAndDecrement(5, 5)
 fmt.Printf("%d", value2)
}
Output is
4

Named return values from a Function 

In all above examples, We are just providing return type in the function declaration. We can also provide return name and type In the below function declaration, the returned statement contains name and type and both are enclosed in ( and )
func Increment(value1 int) (v1 int) {
 v1 = value1 + 1
 return v1
}
func main() {
 value1 := Increment(5)
 fmt.Printf("%d", value1)
}
valid cases for multiple values return for the above code. It is not required to return the value manually. Just return statement is enough. named return value(v1) in declaration ie (v1 int) and body ie.v1 = value1 + 1 should have same name for this case
func Increment(value1 int) (v1 int) {
 v1 = value1 + 1
 return // not required to have return value
}
This is also valid as named value v1 is different from v2, but return statement must be declared with new variable
func Increment(value1 int) (v1 int) {
 var v2 = value1 + 1
 return v2
}
The following code is not valid as return statement in the header is missing ( and ) and it gives compilation error - missing function body syntax error: unexpected int after top-level declaration
func Increment(value1 int) v1 int {
 v1 = value1 + 1
 return v1
}

Variadic functions - variable arguments 

This is one more feature of a function in golang. Function can be declared with variable number arguments. Println is inbuilt in function which accepts variable number of arguments. the syntax for this function declaration
func functionname (arguments ...datatype)
these functions are declared with ellipse (three dots ) in the arguments. This should be declared as last argument.
package main

import "fmt"

func IncrementAndDecrement(nums ...int) int {
 result := 0
 for i := range nums {
  result += nums[i]
 }
 return result
}
func main() {
 res := IncrementAndDecrement(5, 5)
 fmt.Printf("%d", res)
 res1 := IncrementAndDecrement(5, 1, 7)
 fmt.Printf(" %d", res1)
}
and the output is
13
The below code gives compilation error - can only use ... with final parameter in list numbs arguments are not final or last arguments of the function declaration.
func IncrementAndDecrement(nums ...int, string s) int {
 result := 0
 for i := range nums {
  result += nums[i]
 }
 return result
}

closure or anonymous functions 

Golanguage supports function declared without a name. These are called anonymous functions in other programming languages in java and javascript. closure is one type of anonyms functions that can access the variables defined outer function itself. We will see various examples of this two features Function can be used as value and assigned to variable Here function without is declared and assigned to variable, This is being called in other place using variable name with ( and )
var functionName = func() string { // this assigns anonymous function to variable
 return "testvalue"
}

func main() {
 fmt.Printf("%s", functionName())
}
output is
testvalue 
Anonymous functions with inline arguments
The above function can be written in another way by appending argument value inline using ( and )
func main() {
 //Anonymous functin assined to variable by appending argument value inline
 var functionName = func(s string) string {
  return "testvalue " + s
 }("cloudhadoop")
 fmt.Printf("%s", functionName)
}
output is
testvalue cloudhadoop
passing function as an argument
the function can also be passed as an argument to other function, In the following example, Function2 is declared with function argument This function2 is called with supplying argument
func funciton1(value int) int {
 return value * value
}
func funciton2(functionargument func(int) int) int {
 return functionargument(5) 
}
func main() {
 fmt.Printf("%d", funciton2(funciton1))
}
Output is
25
Return type as a function from other function
function declaration contains return type as anonymous function declaration function1 is declared with return type as an anonymous function with argument and return type function caller should be two parameters enclosed ( and ) separately here closure applied as accessed value1 variable inside an inner anonymous function
func function1(value1 int) func(int) int {
 var result = func(value2 int) int { return value1 + value2 }
 return result
}
func main() {
 fmt.Printf("%d", function1(4)(5))
}
Output is
9
Closure with nested function 
a function declared inside other function, outside function variables are accessed inner function nested function is declared inside the main function. fmt class is being declared in the main function and accessed inside nested function value2 is declared in the main function and being accessed in nested function
func main() {
 var value2 = 12
 var nestedFunction = func(value int) int {
  fmt.Println(value)
  return value + value2
 }
 fmt.Println(nestedFunction(6))
}
and output is
6
18

defer statement 

defer is a keyword which is used as a statement in language. Defer is used in function as its execution before function return its value. defer logic always executes before declared function returns its value. defer keyword is declared before a function is declared of a outer function
package main

import "fmt"

func myfunction() (value int) {
 defer func() {
  value = 25
 }()
 return value
}
func main() {
 fmt.Println(myfunction())

}
output is
25

arrays as slice of arguments 

Functions can be passed with an array as an argument, Instead of declaring an array in the function declaration, We can slice the array Function declaration accepts variable arguments using ellipse symbol function caller accepts slicing arrays like myfunction(array1...)
func myfunction(params ...int) int {
 result := 0
 for _, value := range params {
  result += value
 }
 return result
}
func main() {
 var array1 = []int{1, 2, 7}
 fmt.Println(myfunction(array1...))

}
And output is
10
Conclusion
Like every programming language, Functions are building blocks and most useful in go language. There are lot features that functions supported in this language.

Please share your valuable comment or feedback and share it Social Media .

Learn Golang tutorials - Switch case statement guide with examples

This article covers the Switch case statements with expressions and types with various syntax examples.
Learn Golang tutorials - Switch case statement guide with examples

Golang Switch case statements

Switch case is used to execute a particular code block when we have multiple code blocks based on condition. It is an alternative syntax for writing if-else block. Unlike other programming languages like Java and C+, where, the break is needed to stop its execution. Go language is automatically stopped its execution when matching case executed. Break keyword is not required.

There are two types of Switch types in Go Programming language.
  • Expression Switch - In this case, Switch expression are compared with case expressions.
  • Type Switch -Switch expressions types are compared with case expressions.

Expression Switch 

expression switch is used to compare expression with a value of case expressions.
Here is a syntax for switch case
switch (variable|boolean-expression|Integer type){
case boolean-expression | integer type
     Block of code contains statements
case boolean-expression | integer type
     Block of code contains statements
default: // default  case and it is optional
   Block of code contains statements
}
Following are the keynotes of expression switch
  • Switch executes from top to bottom, Stop its execution when a matching case occurs
  • It contains any number of case statements with each case statements contains expression and a colon.
  • the default case is optional. This will be executed when the matching case is not executed. This placed last case and break is not required 
  • Switch expression and case expression must be evaluated to the same type, Otherwise, it gives a compilation error. For example, Switch evaluates to float and case evaluates to float only. 
  • curly braces for case body is optional. 
  • if there are many matched cases, first matched cases are executed.

Example

Here is a basic example of switch case statements
In the below example, Number is declared with value 1. In the switch, number compares with the value of number against all case statements. Here cases are evaluated from top to bottom. Matched first executes its code block, In this case, 1 is matched, 1 matched is displayed to console. switch expression can be enclosed with parenthesis and without parenthesis - both switch number or switch (number) are allowed and valid code.
package main

import "fmt"

func main() {
 number := 1
 switch number {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
Output is
1 matched
Following is various examples of the switch case

The duplicate case with same values are not allowed 

In the below code, the duplicate case is declared with the same values - case 3 is declared two times. The compiler gives compilation error - duplicate case 3 in switch previous case at
package main

import "fmt"

func main() {
 number := 1
 switch number {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 3:// duplciate case is declared here - Compilation error
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}

Default case when the matched case is not declared

what will happens when the number is given as 10? to the same example. the matching case for the number is not defined in code, hence default case will be executed and printed default matched text is printed to the console output

package main

import "fmt"

func main() {
 number := 11
 switch number {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
of the above program is
default matched
The default case is an optional case. It is advisable to be last case statement but there is no effect on the way of switch case functionality

Switch with No expression or Condition 

The switch can also be declared without expression or condition. When no expression is used, It treats switch case as a true value. switch with no expression or condition or value always equals to switch true. case expression always should be expression or condition
package main

import "fmt"

func main() {
 number := 11
 switch {
 case number > 10:
  fmt.Println("Number is greater than 10")
 case number > 20:
  fmt.Println("Number is greater than 20")
 case number > 30:
  fmt.Println("Number is greater than 30")
 default:
  fmt.Println("default matched")
 }
}
and output of the program code is
number is greater than 10
when no expressions in the switch case, case expression must be non-constants
package main

import "fmt"

func main() {
 number := 11
 switch {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
the above code is not compiled The reason is switch without expression code should have case non-constants The compilation error is invalid case 1 in a switch (mismatched types int and bool) Complete error for the command is go run filename
.\First.go:8:2: invalid case 1 in switch (mismatched types int and bool)
.\First.go:10:2: invalid case 2 in switch (mismatched types int and bool)
.\First.go:12:2: invalid case 3 in switch (mismatched types int and bool)
.\First.go:14:2: invalid case 4 in switch (mismatched types int and bool)

Switch case contains multiple expressions or conditions 

Case contains multiple expressions separated by comma symbol


package main

import "fmt"

func main() {
 weekday := "tuesday"
 switch weekday {
 case "monday", "tuesday", "wednesday", "thursday", "friday":
  fmt.Println("Working Day")
 default:
  fmt.Println("Not working day: weekend")
 }
}
The output of the above program is
Working Day
the above code, Code cheks weekday is working day or not. the case is defined with multiple strings which are declared as working days.

fallthrough keyword in the case body 

Normally when the matched case is found with switch case, the code inside matched case executes and control exit from switch case. fallthrough statement is special functionality used to jump the control from next immediate available case fallthrough is a keyword in golang, hence it will not be used as variable or function names.
package main

import "fmt"

func main() {
 number := 1
 switch number {
 case 1:
  fmt.Println("1 matched")
  fallthrough
 case 2:
  fmt.Println("2 matched")
  fallthrough
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
The output of the above program is
1 matched
2 matched
3 matched
without fallthrough statement, The output is
1 matched
In the above code, Control comes to the matched case, case 1 is matched, fallthrough statement exists, Control transfer to the first line of code of next case 2 statement. fallthrough statement is the last statement inside the code of case statement. if you declare fallthrough as not line of code, It gives compilation error the following code gives fallthrough statement out of place
func main() {
 number := 1
 switch number {
 case 1:
  fallthrough // not allowed as first or middle - compilation error
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
  fallthrough
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }

switch case floating values

Switch and case expression can also be declared with floating values and it is valid code. Other languages are not supported to be used in switch case expressions. Golang has no issues with it. The below program contains floating numbers, matched case with floating values are evaluated. In this case, 6.5 matched is printed to the console.
func main() {
 number := 6.5
 switch number {
 case 5.5:
  fmt.Println("5.5 matched")
 case 6.5:
  fmt.Println("6.5 matched")
 default:
  fmt.Println("default matched")
 }
}
and output of the above program is
6.5 matched 

switch case String literals 

allowed Expression can also be string literals. String literals are a group of characters enclosed in double quotes. It checks the exact match of string literals. In the below code, Case contains String literals, Switch expression contain string variable, the Matched case is evaluated, and output is TWO matched
func main() {
 number := "TWO"
 switch number {
 case "ONE":
  fmt.Println("ONE matched")
 case "TWO":
  fmt.Println("TWO matched")
 default:
  fmt.Println("default matched")
 }
}
The output of the above program is
TWO matched

Break statement to exit from the loop

break statement can also be used in switch cases. It is used to exit from the inner loop inside the switch. When you are using for loop with switch case, break keyword will be used. Here is an example without break statement for loop iterates with 3 values, Inside the loop, Switch is declared, and matched cases values are printed.


func main() {
 var numbArray = [3]int{1, 2, 5}
 for _, numb := range numbArray {
  switch numb {
  case 1:
   fmt.Println("1 matched")
  case 2:
   fmt.Println("2 matched")
   break
  case 0:
   fmt.Println("0 matched")
  }
 }
}
Output is
1 matched
2 matched
Now we will rewrite the code with break and named labels in switch case statements In the below loop code, for the first matched case, break label is used, It exists from the named label and output only 1 matched case.
func main() {
 var numbArray = [3]int{1, 2, 5}
MyLoopName:
 for _, numb := range numbArray {
  switch numb {
  case 1:
   fmt.Println("1 matched")
   break MyLoopName
  case 2:
   fmt.Println("2 matched")
   break
  case 0:
   fmt.Println("0 matched")
  }
 }
}
Output is
1 matched

Functions can be used as Expression in switch and case 

the expression can also be a function named calls and valid in go language Following is an example for functions in switch expressions. In the below example, the Simple function is declared, It just returns the passed parameter no value is processed. This is being used in Switch expression as well as case expression.
func myfunction(parameter string) string {
 return parameter
}
func main() {
 switch myfunction("mon") {
 case myfunction("mon"), myfunction("tue"), myfunction("wed"), myfunction("thu"), myfunction("fri"):
  fmt.Println("working day")
 case myfunction("sat"), myfunction("sun"):
  fmt.Println("Not working day: weekend")
 }
}
Output is
working day

Type Switch

Type switch is mostly used in interfaces Type switch is do multiple type checking and evaluates first matched type case. These are mostly used to type assertions Difference between the expression switch and type switch, the Normal switch is compared values with case values. Type switch compares types not values with case types.
Here is a syntax for type switch
switch variable.(type){
case type:
  Code block statements
case type:
  code block statements
default:
  code block statements
}
variable.(type) represents type assertion that contains specific type as "type" Following are key points of the type switch expressions
  • You can define any number of case statements
  • The expression defined in this type always of interface type variable
  • Like a normal switch expression, Default is also optional and last declared, the break is not required.
  • Switch type and case type must be of the same type or follows is-a principal.
  • When switch type and case type is matched, matched case code body is executed, exit from the switch code, Break is not required 

switch type assertion interface example

 In the below example, interface() is an empty interface type that can accept any type of value.
package main

import "fmt"

func main() {
 var interfaceDemo interface{} = 45

 switch interfaceDemo.(type) {
 case string:
  fmt.Println("string type matched")
 case int:
  fmt.Println("int type matched")
 default:
  fmt.Println("default type matched")

 }
}
The output is
int type matched

a type switch struct example 

Type switch case can be used with struct data types. struct types contain custom type which contains multiple types.
package main

import "fmt"

func main() {
 type Employee struct {
  ID   int
  Name string
 }
 emp := Employee{1, "Kiran"}
 var empInterface interface{}
 empInterface = emp
 switch empInterface.(type) {
 case Employee:
  fmt.Println("Employee type matched")
 case string:
  fmt.Println("String type matched")
 default:
  fmt.Println("default type matched")
 }
}
output
Employee type matched
Please share your valuable comments and feedback:) and share it on facebook

Tuesday, November 13, 2018

Learn Golang Tutorials - foreach loop with range keyword examples

In this blog post, We are going to learn for each loop with range in go language with example
for each loop in golang to iterate array,strings,unicode chars,maps

Golang for each loop 

the foreach loop is a for loop with range keyword. It is used iterate each element from Array, Slice, Map, and Strings. This is always useful to iterate the elements of a data structure without getting the length of data structure Syntax of the for with range loop is as follows
for key, value := range collection{
// body
}
During an iteration of the collection, each iteration contains key or index, value or element at index.
Few key points for loop with range keywords
  • This is used to iterate elements of a collections types
  • Each iteration data contains two parts, One is key or index, the second is a value or an element at index 
  • The iterated elements order is not ordered or preserved in a collections
  • use the key as _ for retrieving values during array iteration
  • for array and slice, the first element is an index, the second value is an element at index position for each iteration
  • if the array or slice is empty, It returns nothing

For each array range iteration example

Below is an example for iterate the array of numbers
package main

import "fmt"

func main() {
	// Iterate numeric array
	numbers := [3]int{6, 9, 3}
	for key, value := range numbers {
		fmt.Printf("%d = %d\n", key, value)
	}
}
Output is
0 = 6
1 = 9
2 = 3
For array iteration, the First variable for iteration value can be passed _
func main() {
	// Iterate numeric array
	numbers := [3]int{6, 9, 3}
	for _, value := range numbers {
		fmt.Printf("%d ", value)
	}
}
Output is
6 9 3
another way is using the index parameter of iteration value to traverse the elements of the array
func main() {
	// Iterate numeric array
	numbers := [3]int{6, 9, 3}
	for i := range numbers {
		fmt.Printf("%d ", numbers[i])
	}
}
Output is
6 9 3

Iteration examples with range keyword

The below example covers the following things
  • Iterate elements in Numeric Array 
  • Loop elements in String Array 
  • Iterate elements in Unicode characters of a string
  • Iterate elements in Map
package main

import "fmt"

func main() {

	// Create Numeric array
	numbers := [3]int{6, 9, 3}
	// Iterate numeric array
	for key, value := range numbers {
		fmt.Printf("%d = %d\n", key, value)
	}
	// Create String array
	strs := [3]string{"one", "two", "three"}
	// Iterate String array
	for key, value := range strs {
		fmt.Printf("%d = %s\n", key, value)
	}

	/* create a map*/
	emps := map[string]string{"1": "John", "2": "Franc", "3": "Kiran"}

	/* Iterate map using keys*/
	for emp := range emps {
		fmt.Println("Emp Id: ", emp, " Name: ", emps[emp])
	}
	/* Iterate Unicode charactes of a String*/
	for index, character := range "本語日" {
		fmt.Printf("%#U  position %d\n", character, index)
	}

}
The output of the above program code is
0 = 6
1 = 9
2 = 3
0 = one
1 = two
2 = three
Emp Id:  1  Name:  John
Emp Id:  2  Name:  Franc
Emp Id:  3  Name:  Kiran
U+672C '本'  position 0
U+8A9E '語'  position 3
U+65E5 '日'  position 6

Monday, November 12, 2018

Learn Golang tutorials - For Loop beginner guide with examples

This blog post covers the For Loop with a break, continue, goto keywords with examples in Go Language.
Golang - for loop, break,continue,goto label keywords examples

Golang For loop

For loop is used to execute the code block at a specific number of times. it is one more control structure type in go language. Following is a syntax of for loop
for initialization; conditional Boolean expression; increment|decrement {
 // Code block
}
following are notes of for loop syntax
  • initialization are variables that can be declared and initialized with starting value.
  • the conditional Boolean expression is that results true or false always, if it is true, code block or one iteration executes. Otherwise, the controller will terminate from loop execution. These expressions are created using Comparing operators like ==,!=,= etc.. Expression can be single or multiple. Multiple expression can be combined using logical operators -  &&,||,!
  • Increment/decrement is to change the variable value after code block is executed. parenthesis is not required for this loop.
Here is an example for For Loop. This loop executes 10 times and prints each iteration variable value.
package main
import "fmt"
func main() {
 for i := 0; i < 10; i++ {
  fmt.Print(i)
 }

}
The output of the above code is
0123456789
initialization and increment/decrement are not required of a for loop Here is an example without initialization variable
func main() {
 i := 0
 for ; i <= 10; i++ {
  fmt.Print(i)
 }
}
Here is an example without increment/decrement variable
func main() {
 i := 0
 for i <= 10 {
  fmt.Print(i)
  i++
 }
}
The output of the all the above code is
0123456789

Break statement 

the break is a keyword in golang. It is used to terminates the for loop execution, Controller will be delegated to the next statement after for loop code. This can also be used in a nested loop to terminates the nested loop execution and the controller executes outside loop normal Syntax is
break;
Here is an example of for loop with break statement In this example, Loop executes from 1 to 10 iterations, During 5th iteration, break keyword terminates from For loop execution, and executes the statements after loop code.
func main() {
 i := 0
 for i <= 10 {
  fmt.Print(i)
  if i == 5 {
   break
  }
  i++
 }
 fmt.Print("End")
}
The output of the above program is
012345End
break keyword can also be used with label statements which break the termination Here is an example break label statements
package main

import "fmt"

func main() {
LOOPSECTION:
 for i := 1; i <= 10; i++ {
  if i%2 == 0 {
   break LOOPSECTION
  }
  fmt.Print(i)
 }
 fmt.Print("End")

}
Output is
1End

Continue statement

Continue is a keyword which is used to continue the next loop execution after stop the current execution here is syntax
continue;
Here is an example of for loop with continue keyword usage
func main() {
 for i := 1; i <= 10; i++ {
  if i%2 != 0 {
   continue
  }
  fmt.Print(i)
 }
 fmt.Print("End")

}
Output the code is
246810End
continue keyword can also be used with label statements which jump the execution from the current execution
func main() {
LOOPSECTION:
 for i := 1; i <= 10; i++ {
  if i%2 == 0 {
   continue LOOPSECTION
  }
  fmt.Print(i)
 }
 fmt.Print("End")
}
Output is
13579End

goto label Statement 

goto is a keyword in go language. it is used to jump the iteration to the label statements without checking condition. goto is not recommended to use in any language. The syntax is as follows
goto LabelName;

LabelName: code;
Here is an example for goto label statement of for loop for loop iterates from 1 to 10, When 5 iteration is encountered, It skips the 5th value to console.
func main() {
 i := 1
LOOPSECTION:
 for ; i <= 10; i++ {
  if i == 5 {
   i++
   goto LOOPSECTION
  }
  fmt.Print(i)
 }
 fmt.Print("End")

}
The output of the above code is
1234678910End

Learn Golang tutorials - While loop beginner guide with examples

This blog post covers learn while and do while loop guide with examples in Golang.
Golang - while or do while loop examples

Golang while loop 

Like other programming languages, There is no while loop or do while loop in go language. Instead, it provides for loop with a boolean expression. This will executes code of block multiple times until conditional expression is true. if conditional expressions result false, It exits the control from the loop block. Each iteration is executed once the condition is true. Conditional expressions are evaluated and executed before each iteration. Here is the syntax for the while loop alias for loop with a boolean expression
for boolean-expression {
// code block
}
boolean-expression results true of false always. These expressions are created using comparison operators. multiple-expression can also be defined using logical operators. Infinite for loop code block executes infinite times. This conditional boolean expression will never be true. We can write in multiple ways using for expression for without boolean expression. In this case, Condition expression is omitted
func main() {
 number := 1
 for {
  number++
  fmt.Println(number)
 }
}
or other way using for with true boolean values. The boolean expression is always true.
func main() {
 number := 1
 for true {
  number++
  fmt.Println(number)
 }
}
The above programs return the output as follows
1
2
3
...
Infinite times

while loop sleep - wait a time before looping 

while loop alias for loop used to loop the code block. we are going to use sleep function in time package waits for controller before looping code block. time is a builtin package as part of golang. This package provides different functionalities dealing with time-related things. package time inbuilt sleep function waits 300 milliseconds for each iteration during an infinite loop
package main

import (
 "fmt"
 "time"
)

func main() {
 number := 1
 for true {
  number++
  fmt.Println(number)
  time.Sleep(300 * time.Millisecond)// control stops here and sleeps for 300 milli seconds

 }
}

Learn Golang Tutorials - if else statement examples

In this blog post, we are going to learn control flow structures - if-else statements in Go Language with examples.
Learn Golang Tutorials - if else statement examples

golang if statements

Like many programming languages, Go Language provides control structures for decision making. if and else statements are one of type.if statements are used to execute a piece of code based on the conditional expressions, if the condition is satisfied, code block will be executed.
This blog post covers examples and syntaxes for the following things
  • simple if statements
  • if shorthand statements
  • if else statements
  • if else nested statements
Here is Syntax for if statements in Golang
if(Conditional Expression) {
Code Block
}
conditional expression is evaluated and always results true or false. the expression can be made of simple boolean values or complex expression created using comparison operators ==,= or !=. the expression can be single or multiple. Multiple expressions are joined with logical operators like &&,||,! operators. Conditional Expressions are not required to be enclosed with parenthesis, But code block must be enclosed with curly braces In golang, curly braces are required for code block which contains sing statements.

simple if statement 

This example evaluates the expression if the expression is true, the code block is executed and return "Event Number test passed " to console The below is an example for simple if the conditional expression
package main

import "fmt"

func main() {
	var numerVariable = 10
	if numerVariable%2 == 0 {
		fmt.Printf("Event Number test passed ")
	}
}
the output of the above code is
Event Number test passed 
below example code give a compilation error, The reason is if statements code block has no curly braces, It throws syntax error: unexpected newline, expecting { after if clause
package main

import "fmt"

func main() {
	var numerVariable = 10
	if numerVariable %2 == 0 
		fmt.Printf("Event Number test passed ")
}
Multiple expression can be combined with logical operators
var number = 2
if  number >= 1 && age <= 10 {
	fmt.Println("Number is between 1 to 10")
}	

if with shorthand statements 

In this, if statement always contains the shorthand statements, before going control to the conditional expression. shorthand statements can contain variable declaration and the scope of the variable are the scope of this block only
func main() {
	var numerVariable = 10
	if result := numerVariable % 2; result == 0 {
		fmt.Printf("Event Number test passed ")
	}
}
if you include shorthand syntax in if statements, the parenthesis is not required. It gives compilation error - syntax error: unexpected :=, expecting ), if parenthesis is in shorthand syntax
func main() {
	var numerVariable = 10
	if (result := numerVariable % 2; result == 0) {
		fmt.Printf("Event Number test passed ")
	}
}

if and else statement 

This syntax contains else block for if statement. if conditional expression is true if the block is executed, otherwise else block is executed.
if (conditional expression){
if true this block of code is executed
}else{
if false block of code is executed
}
example for if else statement
package main

import "fmt"

func main() {
	var numerVariable = 10
	if numerVariable%2 == 0 {
		fmt.Printf("Event Number if block ")
	} else {
		fmt.Printf("Odd Number else block")

	}
}
the output of the above program is
Event Number if block

multiple if else - nested if statements 

if the statement contains if else statements that contain chains of if else statements
package main

import "fmt"

func main() {
	var numerVariable = 1001
	if numerVariable <= 100 {
		fmt.Printf("Number is less than 100")
	} else if numerVariable > 100 && numerVariable <= 1000 {
		fmt.Printf("Number is greater than 100 and less than 1000")
	} else { // else statements
		fmt.Printf("Number is greater than 1000")
	}
}
The output of the above program is
Number is greater than 1000
Compilation error if any line breaks before else statement as like below example the below program gives syntax error: unexpected else, expecting }
func main() {
	var numerVariable = 1001
	if numerVariable <= 100 {
		fmt.Printf("Number is less than 100")
	} else if numerVariable > 100 && numerVariable <= 1000 {
		fmt.Printf("Number is greater than 100 and less than 1000")
    } 
    else { // else statements
		fmt.Printf("Number is greater than 1000")
	}
}

Learn Golang Tutorials - Data types Basic Guide with examples

In this blog post series, We are going to learn basic inbuilt predefined data types in golang tutorials with examples.
Learn Golang Tutorials - Data types Basic Guide

Go language data types

Go is a modern opensource programming language from Google.
It is a static type language which means type checking will be done at compile time. Variable can be declared a type or inferred from type inference.
datatypes in golang define the same type of data that can be used to allocates memory size for storing the particular value.

It has several built-in types similar to any programming language.

There are several data types that can be categories based on similar data types
  • Numeric types - This represents numeric numbers which can be divided into Integers, Floating and other types
  • String types - This represents a group of characters
  • Boolean types - It represents boolean values - true or false
  • Custom Data types - It Contains different types like pointers, Array, Struct, Union, Map, and Channel types

Integer data types

These are used to store the positive and negative numbers including zero. It has various types based on size and signed types.

Signed Integer types

signed integer allows the values positives and negatives including zero. it also has int data type which changes based on machine environment
Inbuilt Type Size in bytes Range of values
int8 1 Byte -128 to 127
int16 2 Bytes -32768 to 32767
int32 4 Bytes -2147483648 to 2147483647
int64 8 Bytes -9223372036854775808 to 9223372036854775807

Unsigned Integer types 

Unsigned integer allows the values positive values including zero. It does not allow negative values
Inbuilt Type Size in bytes Range of values
uint8 1 Byte 0 to 255
uint16 2 Bytes 0 to 65535
uint32 4 Bytes 0 to 4294967295
uint64 8 Bytes 0 to 18446744073709551615
Other Numeric types 
There are other numeric types byte etc..


Inbuilt Type Size in bytes Range of values
byte 1 Byte same as uint8
rune 2 Bytes int32
uint 4 Bytes or 8 bytes based on Environment
int 4 Bytes or 8 bytes/td>Based on Environment
uintptr 4 Bytes or 8 bytes/td>unsigned int to store pointer bits

Example

This example covers the following things
  • Type inference example
  • The octal number always prefixed with 0
  • Hexadecimal number prefixed with 0x
This has no char data type in java language. byte and rune are used to represent char types. a byte represents characters in ASCII values. rune represents in UNICODE character in the UTF-8 format
package main
import "fmt"
func main() {
 var int16Variable int16 = 12
 var intVariable = 85 // Type inference example
 var uintVariable uint = 40
 var hexVariable = 0xBC  
 var octalVariable = 013 
 fmt.Printf("%d, %d, %d, %#x, %#o\n", int16Variable, intVariable, uintVariable, hexVariable, octalVariable)
 var byteVariable byte = 'C'
 var runeVariable rune = 'a'
 fmt.Printf("%c - %d and %c - %U\n", byteVariable, byteVariable, runeVariable, runeVariable)

}
The output of the above program is
12, 85, 40, 0xbc, 013
C - 67 and a - U+0061

Floating numeric types 

Like any programming language, These are used to represents numbers with decimal values(3.21) for example, when you declared float value like this, compiler infer the type as float64. The default type is float64
var floatVariable = 47895.587
And also complex data type default type is complex128. type inference applied on complex number also complex128
var complexVariable = 1 + 6i  
Type Size in bytes Description
float32 4 Bytes IEEE-754 Floating numeric values
float64 8 Bytes IEEE-754 Floating numeric values
complex64 8 bytes Complex numbers with float32 real and imaginary parts
complex128 4 Bytes or 8 bytes/td>Complex numbers with float64 real and imaginary parts

Boolean Datatypes 

Go language has data type bool to store boolean values. It has predefined values true or false

var boolVariable = true
var booleVariable1 bool = false

String Datatype 

The string is a group of characters. Characters in golang treated as bytes. The string can be declared using double quotes or backticks. Double quotes enclosed strings cannot be multiple lines but contains newline characters \n. Backticks enclosed string can contain multiple lines
var str1 = "Cloud Hadoop Blog"

var str2 = `This is programming blog for 
   full stack technolgies`
 

Java Unique Number Generator - UUID or GUID with examples

In this blog post, We are going to learn java Unique Number Generator-  UUID or GUID with examples.

You can also check my previous articles on 
There are two types of unique identifiers. UUID is a universally unique identifier, GUID is a globally unique identifier, The difference between UUID and GUID, Both are returning 126 bits,
GUID is Microsoft implementation of UUID functionality. Both generates 16 bytes hexadecimal separated by a hyphen in four groups.
UUID or GUID can be used in the following in real time

  • Used to represent a primary key in a database table
  • can be used as Session ID in web applications, Transaction Id in enterprise applications
  • Can also be used as unique identifier for doing CRUD operations in  REST API applications
  • Represents to identify big data spread across multiple servers
  • Naming static resources for storing and retrieving files.
Java provides java.util.UUID class for providing UUID implementation in java

java.util.UUID class 

This class is specified as an immutable universally unique identifier (UUID).  This class has following notes about it
  • Generates 128 bit or 16 bytes that contains hexadecimal values 
  • Implements Serializable, Comparable interfaces
  • Extends Object class.
There are multiple variants for creating UUID. It has methods for operating Leach-Salz variant. but it has a constructor to support all variants
Constructor
UUID(long mostSigBits, long leastSigBits)
It has only one constructor which takes two parameters to create a new UUID mostSigBits - most significant bits 64 bits of UUID
leastSigBits - least significant 64 bits of UUID
UUID has four types of versions
  • Version 1 represents time-based - UUID V1 
  • Version 2 represents DCE security - UUID V2 
  • Version 3 represents name-based - UUID V3 
  • Version 4 represents Random generated - - UUID V4

Example

The below example generates UUID V4 string
import java.util.UUID;

public class UUIDDemo {

 public static void main(String[] args) {
  
  UUID uuid = UUID.randomUUID();
  String uuidString = uuid.toString();
  System.out.println(uuid.variant());  // 2
  System.out.println(uuid.version());  // 4
  System.out.println(uuidString);  //3d795ac3-2cea-4ed2-92d8-3d71a2539cf2

 }

}

java-uuid-generator maven 

In maven applications, java-uuid-generator is a dependency from com.fasterxml.uuid. This is a java library for generating UUID with all versions

<dependency>
    <groupId>com.fasterxml.uuid</groupId>
    <artifactId>java-uuid-generator</artifactId>
    <version>3.1.5</version>
</dependency>
The below example generates the following thins

  • UUID V1 Generation using timebase generator 
  • UUID V3 Generation using UUID.nameUUIDFromBytes method as well as name based
  • UUID V4 Generation using randomBasedGenerator 
  • UUID V5 Generation using SHA digester 
import java.util.UUID;

import com.fasterxml.uuid.Generators;

public class HelloWorld {
 public static void main(String[] args) {
  // UUID V1 generation
  UUID v1 = Generators.timeBasedGenerator().generate();
  System.out.println("UUID V1 value: " + v1.toString());
  System.out.println("version  : " + v1.version());
  System.out.println("variant  : " + v1.variant());
  // UUID V3 generation
  //  create byte array and initialize it
  byte[] byteArray = { 0, 1, 4 };
  // Create uuid from byte array
  UUID v3 = UUID.nameUUIDFromBytes(byteArray);
  System.out.println("UUID V4 value: " + v3.toString());
  System.out.println("version  : " + v3.version());
  System.out.println("variant  : " + v3.variant());
  // UUID V4 generation
  UUID v4 = Generators.randomBasedGenerator().generate();
  System.out.println("UUID V4 value: " + v4.toString());
  System.out.println("version  : " + v4.version());
  System.out.println("variant  : " + v4.variant());

  // UUID V5 generation
  UUID v5 = Generators.nameBasedGenerator().generate("cloudhadoop.com");
  System.out.println("UUID V5 value: " + v5.toString());
  System.out.println("version  : " + v5.version());
  System.out.println("variant  : " + v5.variant());


 }
}
Output of the above program code is
UUID V1 value: 04272c28-e69d-11e8-be73-df7930994371
version  : 1
variant  : 2
UUID V4 value: be489ef3-af30-3d20-b50a-5c504ecc5294
version  : 3
variant  : 2
UUID V4 value: 1c4e3ff8-bf58-4081-8e3f-f8bf58908109
version  : 4
variant  : 2
UUID V5 value: cdecd331-e6c2-5e7f-ad1d-3ee766052560
version  : 5
variant  : 2

How to create UUID from a String 

UUID class provides fromString() method which generates UUID from a given string. This is an example for Converting String to UUID. This method throws Exception in thread "main" java.lang.IllegalArgumentException: Invalid UUID string: 150e064ff8d6, if string is not 16 bytes in length

import java.util.UUID;

public class fromStringExample {

 public static void main(String[] args) {

  UUID uuid = UUID.fromString("d4578015-0e06-4ff8-9780-150e064ff8d6");
  System.out.println("UUID  value: " + uuid.toString());
  System.out.println("version  : " + uuid.version());
  System.out.println("variant  : " + uuid.variant());
 }

}
The output of the above code is

UUID  value: d4578015-0e06-4ff8-9780-150e064ff8d6
version  : 4
variant  : 2
UUID class methods

UUID class methods

  • clockSequence - this method returns clock sequence for given UUID. It throws Exception in thread "main" java.lang.UnsupportedOperationException: Not a time-based UUID.if it is not time-based UUID version
  • getLeastSignificantBits - This method returns least significant 64 bits of given UUID
  • getMostSignificantBits() - This method returns m significant 64 bits of given UUID
  • nameUUIDFromBytes(bytearray) - this method returns UUID V3  for given byte array
  • node()- This method return node value of given UUID 
  • timestamp() - This return timestamp of given UUID
  • randomUUID - This static method generates random UUID

Other UUID libraries 

There are various UUID libraries available for java language-markup

Learn Golang tutorials - Variables starter guide with examples

In this blog post, It covers the Golang Tutorials variables  guide with examples
Learn Golang tutorials - Variables starter guide with examples

Golang Tutorials variables

Variables usage in go language is same as like another programming language like java. Variables are the name assigned for a space in memory that saves the values.  Variables of different types. Based on each type, memory size will be accommodated

Variables name can be named using letters, digits and underscore characters. Go lang is case sensitive so that upper and lower names are different. Variables in go language are declared using var keyword. before using any variables, you need to first declare it.

Variable declaration

Variables can be declared using var keyword, Once variable is declared, the compiler allocates memory based on the type of the variable. The variable declaration contains three parts 1. var keyword 2. variable name 3. type of variable
var variablename(s) variableType
can be a single variable or multiple variable types are predefined inbuilt types or custom types. Inbuilt types can be byte, int and float32 and string. Following are a various way of variable declaration examples
initialized variables
It can be declared and initialized with values. This can be done in many ways
The following example explains converting different types
package main
import (
	"fmt"
)
func main() {
	m := 42
	n := float64(2.0)
	var o float64 = float64(25.2)
	fmt.Println(m)
	fmt.Println(n)
	fmt.Println(o)

}
Output is
42
2
25.2
Multiple variable declarations 
Here multiple variables can be declared in a single line of the same type
var  a,b,c int;
var (
  m = 1
  n = 20
  o = 3
)
Short variable declarations 
variables can be declared and assigned with initial values. Multiple variables can be declared in a single line and readability is improved and code lines reduced
package main
import "fmt"
func main() {
	var m, n int = 10, 20
	fmt.Println(m, n) // 10 20
}

Global Scope 

variables declared outside function blocks and at the package level. This variable can be accessed across all functions declared in the program. These variables can exist as long as the program is running
package main

import "fmt"

//Global Variables Declaration
var globalVariable="Hello";
func main() {
	fmt.Println(globalVariable);

}
and output of the above code is
Hello

Local Scope 

variables declared inside a function or block of a code is called local variable. The variables cannot be accessed outside the function
package main
import "fmt"
func main() {
	//Local Variables Declaration
    var localVariable="this is test variable";
	fmt.Println(localVariable);

}
and output of the above code is
this is test variable 

Variables default values 

variables are assigned with a default value when variables are assigned with initial values zero for number types like Int, Float etc.. false for Boolean types empty string - "" for Strings


package main

import "fmt"

func main() {
	var intVariable int32
	var floatVariable float32
	var booleanVariable bool
	var strVariable string
	fmt.Printf("%v %v %v %q\n", intVariable, floatVariable, booleanVariable, strVariable) // output 0 0 false ""

}

type inference 

type inference is called When a variable is declared without the type of the variable. variable type can derive the type from the right-hand side of the value. inference can be applied to variables and constants Below example descript using variable expression using = and := operators
package main
import "fmt"
func main() {
	var k int
	l:=k
	var m = 42 
	var n = false 
	p:=3.2 // constant 
	fmt.Printf("variable k datatype is %T\n", k)
	fmt.Printf("variable l datatype is %T\n", l)
	fmt.Printf("variable m datatype is %T\n", m)
	fmt.Printf("variable n datatype is %T\n", n)
	fmt.Printf("variable p datatype is %T\n", p)

}
the output of the above program code is
variable k datatype is int
variable l datatype is int
variable m datatype is int
variable n datatype is bool
variable p datatype is float64

Constants declaration 

Constants are like variables which can not be changed its value once the value is assigned. whereas a variable can be changed. Constants can be declared using := syntax. const can be applied to all types of variables like boolean, strings and numeric types
package main
import "fmt"
func main() {
	const str = "kiran"
	fmt.Println("Hi", str) // Hi kiran
	const booleanValue = true
	fmt.Println(booleanValue) // true
}

How to find a memory or address location of a variable ie variable pointer reference memory

memory for variables in golang can be referenced using  & variable name - ampersand variable. 
  • & the variable is a pointer of a variable which prints memory location of the variable 
  • *& the variable is a value of a variable at memory location
This example prints the pointer of a variable
package main
import "fmt"
func main() {
   var m int
    fmt.Println("memory location for m :", &m, "variable value is ", *&m)
    n:= 15
    fmt.Println("memory location for n :", &n, "variable value is ", *&n)
}
Output of the above code is
memory location for m : 0x416020 variable value is  0
memory location for n : 0x416024 variable value is  15

Learn Golang tutorials - Install and setup Go language on Windows

In this blog post, We are going to learn an easy way to install go language on windows.
Golang installation on windows

Go Language installation 

Go is a modern popular opensource programming language. Go language is developed by Google. It provides binary versions for Windows, MacOS, and Linux officially. If you want to install different environment, You can get the source code and built it to your platform.
Go language provides the following binaries for installation on different environments
  • Windows
  • Apple MacoOS
  • Linux
  • Ubuntu

Installation and Setup on Windows

First get the binary installer for windows ie MSI file from and download it. It downloads MSI file

Once the download is completed, Install MSI file and select A:\Golang location  follow the next steps

Next step is to configure environment variables

Configure Environment Variables

Go to My Computers or This PC --> properties --> Advance System Settings --> Environment Variables, Create a System variable or environment variable GO_ROOT
give the value of  GO_ROOT to A:\Golang folder
Next, configure GO_ROOT to PATH variable ie set PATH to %PATH%\%GO_ROOT%\binary
This installs the Go Language successfully

Check Golang Installation 

To check the installation, first Open command line shell and give "go version" command, This gives go language version correctly

C:\>go version
go version go1.11.2 windows/amd64

C:\Users\Kiran>go env
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\Kiran\AppData\Local\go-build
set GOEXE=.exe
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOOS=windows
set GOPATH=C:\Users\Kiran\go
set GOPROXY=
set GORACE=
set GOROOT=A:\Golang
set GOTMPDIR=
set GOTOOLDIR=A:\Golang\pkg\tool\windows_amd64
set GCCGO=gccgo
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=C:\Users\Kiran\AppData\Local\Temp\go-build682765038=/tmp/go-build -gno-record-gcc-switches

Create a First sample Program 

using any IDE or editor, Write the first program and save this file as "First.go" package main
package main
import "fmt"

func main() {
    fmt.Printf("Hello, World")
}
To compile First.go file, Use go build command

A:\Golang\work>dir
 Volume in drive A is Work
 Volume Serial Number is C682-8F53

 Directory of A:\Golang\work

12-11-2018  14:54    <DIR>          .
12-11-2018  14:54    <DIR>          ..
12-11-2018  14:49                83 First.go
               1 File(s)             83 bytes
               2 Dir(s)  125,885,014,016 bytes free

A:\Golang\work>go build First.go

A:\Golang\work>dir
 Volume in drive A is Work
 Volume Serial Number is C682-8F53

 Directory of A:\Golang\work

12-11-2018  14:54    <DIR>          .
12-11-2018  14:54    <DIR>          ..
12-11-2018  14:54         1,969,152 First.exe
12-11-2018  14:49                83 First.go
               2 File(s)      1,969,235 bytes
               2 Dir(s)  125,883,043,840 bytes free

A:\Golang\work>
Execute the First.exe file by following command

A:\Golang\work>First.exe
Hello World