Wednesday, December 12, 2018

Golang Example programs

Go is a Static typed popular programming language. To learn a new programming language, We must write a practical example by making use of features. This is an index page for all golang features like control statements -loops, if else, datatypes, data structures, classes, and objects.

All the programs and examples are compiled and tested and given output.
if you are new to go language, want to learn golang before working on this program, then have a look Golang Tutorials.

Golang Programs

Golang examples - Program to add/sum of two numbers or integers

In this program,  we have two programs to add two numbers. The First program, We will store the numbers and the addition of two numbers. The second program, take the two numbers from the user and return the sum of two numbers.

Example: Sum of two numbers 

In this program, variables are declared and did inline assignment statements. This is one way of declaring multiple variables of the same type in golang 
The same way can be rewritten using short assignment operator as below n1, n2, result := 10, 3, 0 .
The variable types can be inferred from right hand values
package main

import (
 "fmt"
)

func main() {
 var n1, n2, result = 10, 3, 0 // Declare variable and assign values
 result = n1 + n2
 fmt.Println("Sum of two numbers: ", result)

}
Output is
Sum of two numbers:  13 

Scanln function example -Sum numbers taken input from the standard console  

 In this program, numbers are taken from the standard console. Scanln function is used to stop the control until user is entered the number And sum of this two numbers are returned to console
package main

import (
 "fmt"
)

func main() {
 fmt.Print("Please enter first number: ")
 var n1 int
 fmt.Scanln(&n1) // take input from user
 fmt.Print("Please enter Second number: ")
 var n2 int
 fmt.Scanln(&n2) // take input from user
 result := n1 + n2
 fmt.Println("Sum of two numbers: ", result)

}
Output is
Please enter first number: 12
Please enter Second number: 34
Sum of two numbers:  46

Golang Example - Convert(Cast) String to Float and Float to String

This post covers how to convert(cast) String type to float type or float type to String with an example.

Golang strconv package

The string is a group of characters referenced by a variable. A float is a numeric number that stores set of all IEEE-754 64-bit floating-point numbers. Both are of different types, Automatic conversions will not occur. The developer needs to write a code to handle this. Golang provides standard inbuilt package strconv to do string conversions to other types. It is a common task of the developer to convert String to float or float to String.

Convert String to float example

strconv package provides ParseFloat function to convert to float numeric types. You can check more about this function here 
Here is syntax
func ParseFloat(s string, bitSize int) (float64, error)
arguments are
The string is an input string. if given string is not numeric, It gives error strconv.ParseFloat: parsing "abc": invalid syntax
bisize is of int type with values 32 or 64.
Here is a strconv  ParseFloat function example program
package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 floatString := "587.23"
 floatNumb, err := strconv.ParseFloat("abc", 32)
 fmt.Println(floatNumb)
 fmt.Println(reflect.TypeOf(floatNumb))
 fmt.Println(err)
 if n1, err := strconv.ParseFloat(floatString, 32); err == nil {
  fmt.Printf("%T, %v\n", n1, n1)
 }
 if n2, err := strconv.ParseFloat(floatString, 64); err == nil {
  fmt.Printf("%T, %v\n", n2, n2)
 }

}
An output of the above program
0
float64
strconv.ParseFloat: parsing "abc": invalid syntax
float64, 587.22998046875
float64, 587.23

Convert float number to String example

There are two ways to convert float type to String type
one is using fmt.Sprintf() function, other is using strconv.FormatFloat function

fmt Sprintf function example

fmt package provides Sprintf is used to convert to string
Here is a syntax
func Sprintf(format string, a ...interface{}) string 

the format is a string
%f - Decimal format
%e - scientific notation format
%.5f- the precision with 5 format
%g - exponent format

and parameter a is of the vardiac interface which accepts any type of value

Here is a fmt Sprintf function example program 
package main

import (
 "fmt"
 "reflect"
)

func main() {
 str := fmt.Sprintf("%f", 45.1) //45.100000
 fmt.Println(reflect.TypeOf(str))
 fmt.Println(str)
 str1 := fmt.Sprintf("%e", 45.1) //4.510000e+01
 fmt.Println(reflect.TypeOf(str1))
 fmt.Println(str1)
 str2 := fmt.Sprintf("%.5f", 45.1) //45.10000
 fmt.Println(reflect.TypeOf(str2))
 fmt.Println(str2)
 str3 := fmt.Sprintf("%g", 45.1) //45.1
 fmt.Println(reflect.TypeOf(str3))
 fmt.Println(str3)
}
Output is
string
45.100000
string
4.510000e+01
string
45.10000
string
45.1

strconv FormatFloat function example 

strconv package has FormatFloat function is to convert the floating number to string with a given format and precision Here is a syntax of this function
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
Arguments are

floating number converted to a string
fmt is of byte contains values b -binary exponent, e or E - Decimal exponent, F - no exponent, g or G - large exponents
prec  is of int precision value
bitSize is of int type which contains 32 and 64 values Here is an strconv FormatFloat function example program
package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 floatNumb := 5.789455
 str := strconv.FormatFloat(floatNumb, 'f', 5, 64)
 fmt.Println(reflect.TypeOf(str))
 fmt.Println(str)
 str1 := strconv.FormatFloat(floatNumb, 'e', 5, 64)
 fmt.Println(reflect.TypeOf(str1))
 fmt.Println(str1)
 str2 := strconv.FormatFloat(floatNumb, 'g', 5, 64)
 fmt.Println(reflect.TypeOf(str2))
 fmt.Println(str2)
}

Output is
string
5.78946
string
5.78946e+00
string
5.7895 

Tuesday, December 11, 2018

Golang Recursion - Recursive function with examples

In this blog post, we are going to learn Recursive functions in golang with examples.

golang recursive function

Recursion is general programming code process in which method or function calls itself continuously. Go Language support recursion using functions. In Golang, function call itself is called recursive function. Using this technique, It allows code simple but complex to understand the code.

 Important key points of recursion function.
  • Function called inside the same function
  • It is always good to specify an exit condition in the recursive function
  • It reduces unnecessary function calls and code lines 
  • Disadvantages with recursion is code is logical and difficult to debug and inspect the code

Syntax

// function declaration
func recursefunction(){
//Code statements
recursefunction();//function call itself
}
func main(){
recursefunction() // Initialize first normal call
}
In the above syntax, the recursive function is being called inside the same function. Recursion process continues execution until the condition is met. otherwise, function executions in infinite recursion We can prevent infinite recursion using if else statements, if block executes recursive calls, else block will break the recursive call

Golang Recursion function Example: Infinite times 

function recursivefunction is declared. This will be called inside the main function during a normal first call. recursivefunction() is called inside same function. This will be executed infinite times. We have to issue a manual CTRL +C keyword to exit from the program execution
package main

import (
 "fmt"
)

func recursivefunction() {
 fmt.Println("welcome")
 recursivefunction()
}

func main() {
 recursivefunction()
}
Output is
welcome
welcome
welcome
.....
infite times

Golang Recursion function Example: finite times

In the below example recursive function is declared and called inside the main function at first during the normal first function call. the same function is called recursively inside the same function. This recursive call executes 10 times and exit from the recursive function. if statement is used to exit from the function.
package main

import (
 "fmt"
)

var count = 0

func recursivemethod() {
 count++
 if count <= 10 {
  fmt.Println(count)
  recursivemethod()
 }
}

func main() {
 recursivemethod()
}
Output is
1
2
3
4
5
6
7
8
9
10

Recursion function Example generates Factorial Number 

A recursive function is declared to calculate a factorial. This return factorial of a number here is a program code for calculating the factorial number.
package main

import "fmt"

func factorial(numb int) int {
 if numb == 0 {
  return 1
 }
 return numb * factorial(numb-1)
}

func main() {
 result := factorial(5)
 fmt.Print("Output for Factorial of 5 :", result)
}
Output is
Output for Factorial of 5 :120

Recursion example for calculating Fibonacci series 

The following program calculates and returns the Fibonacci series for a given input number using a recursive function
package main

import "fmt"

func fibonacci(value int) int {
 if value == 0 || value == 1 {
  return value
 }
 return fibonacci(value-2) + fibonacci(value-1)
}
func main() {
 result := fibonacci(10)
 fmt.Print("Output for Fibonacci series  of 10 :", result)
}
Output is
Output for Fibonacci series  of 10 :55

Recursive anonymous function 

The anonymous function is a function without a name. Recursive functions can be declared as anonymous also.
Following is example program for Recursive anonymous function in golang
package main

import "fmt"

func main() {
 var myfunction func()
 myfunction = func() {
  fmt.Println("Anonymous function example")
  myfunction()

 }
 myfunction()

}
Output is
Anonymous function example
Anonymous function example
...
...
...
infinite times

Monday, December 10, 2018

Golang Example - strconv ParseFloat function guide

This blog post covers package strconv ParseFloat Function with examples in the Go Language.
Golang Example - strconv ParseFloat function guide

golang strconv ParseFloat function

strconv is a standard inbuilt package in go language that provides various function implementations for converting a string to types into an int, float, boolean etc..
String to float is a common task of a programmer during development
ParseFloat is an inbuilt function, converts a String value to a floating  number
You can check official documentation is here
Here is the syntax of this function
func ParseFloat(inputstring string, bitSize int) (float64, error)
Argument list
inputstring is a numeric floating number represented in string bitSize is int type argument of precision value. It can be 32 for float32 or 64 for float64
Return type 
This function always returns two values. The float64 value is returned which contains a floating number.we can convert to float32 value if required. the error is returned with *NumError value if unable to convert a string to a floating number

function usage - success and error cases 

Following are various uses cases of converting a string to floating types In the below code, ParseFloat() function takes a string and convert it to a floating number with given precision of 64. For Conversion, 64bits are considered. Go language uses IEEE_754  binary format for storing floating numbers Returned floating number of type float64 and error-nil is returned.
floatNumb, err := strconv.ParseFloat("123.3412312312", 64)
fmt.Println(floatNumb)
fmt.Println(reflect.TypeOf(floatNumb))
fmt.Println(err)
Output is
123.3412312312
float64
<nil>
Now we will see changing precision value from 64 to 32
floatNumb, err := strconv.ParseFloat("123.3412312312", 32)
 fmt.Println(floatNumb)
 fmt.Println(reflect.TypeOf(floatNumb))
 fmt.Println(err)
 
output is
123.34123229980469
float64
<nil>
The below example gives an error - strconv.ParseFloat: parsing "abc": invalid syntax when given input string is not numeric In this case, this function returns 0 value of type float64 and err contains a description of an error
floatNumb, err := strconv.ParseFloat("abc", 32)
 fmt.Println(floatNumb)
 fmt.Println(reflect.TypeOf(floatNumb))
 fmt.Println(err)
 
Output is
0
float64
strconv.ParseFloat: parsing "abc": invalid syntax

ParseFloat function Example program

Here is an example for Converting string to float64 numbers using parseFloat.
package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 floatString := "12545.23"
 floatNumb, err := strconv.ParseFloat("abc", 32)
 fmt.Println(floatNumb)
 fmt.Println(reflect.TypeOf(floatNumb))
 fmt.Println(err)
 if n1, err := strconv.ParseFloat(floatString, 32); err == nil {
  fmt.Printf("%T, %v\n", n1, n1)
 }
 if n2, err := strconv.ParseFloat(floatString, 64); err == nil {
  fmt.Printf("%T, %v\n", n2, n2)
 }

}
Output is
0
float64
strconv.ParseFloat: parsing "abc": invalid syntax
float64, 12545.23046875
float64, 12545.23

Convert String to float64/float32 values

ParseFloat() function returns float64 value by default. float32(float64value) function used to convert to float32 value Here is an program code for casting string to float64/float32
package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 floatNumb, err := strconv.ParseFloat("123.23", 32)
 fmt.Println(floatNumb)
 fmt.Println(reflect.TypeOf(floatNumb))
 fmt.Println(err)
 float32Value := float32(floatNumb) // Convert to float 32
 fmt.Println(float32Value)
 fmt.Println(reflect.TypeOf(float32Value))
}
Output is
123.2300033569336
float64
<nil>
123.23
float32

Tuesday, December 4, 2018

golang examples - Hostname and IP address programs code

Golang hostname

The hostname is a label assigned to a machine which is connected in Network of machines. Golang standard package net provides functions related to TCP/IP, UDP and DNS related networking related functionalities

The following are various examples related to the hostname and Ip addresses in Go Language.

Get Hostname of the System environment

It is always good to know the hostname of the environment where the go program is running.package standard inbuilt os provides hostname function which gives hostname of the environment. You can check here  for more information
 here is the syntax of hostname function
func Hostname() (name string, error error)
It returns name - hostname and error return nil if no error exists For example if you are running on a System named 'system1', os.Hostname() function returns 'system1' as an output.
Following is an example of finding hostname of the System
package main

import (
 "fmt"
 "os"
)

func main() {
 hostname, error := os.Hostname()
 if error != nil {
  panic(error)
 }
 fmt.Println("hostname returned from Environment : ", hostname)
 fmt.Println("error : ", error)

}
Output is
hostname returned from Environment :  DESKTOP-47884kl
error :  <nil>

Check a string contains IP address or Hostname or domain name

This program is to check a given string is IP address or hostname. net package provides ParseIP() function for checking IP address with the format of IPV4 (192.134.1.12) and IPV6 (1111:ca7::57) Here is a syntax of ParseIP() function
func ParseIP(s string) IP
if given string is not valid IP address representation, It returns nil. Here is a program for checking hostname or IP address of a given string
package main

import (
 "fmt"
 "net"
)

func checkStringForIpOrHostname(host string) {
 addr := net.ParseIP(host)
 if addr == nil {
  fmt.Println("Given String is a Domain Name")

 } else {
  fmt.Println("Given String is a Ip Address")
 }
}
func main() {
 checkStringForIpOrHostname("google.com")
 checkStringForIpOrHostname("192.168.1.0")

}
Output is
Given String is a Domain Name
Given String is a Ip Address

How to get Domain name from a given URL

Often, we need to check Domain name from the given URL. For example, if Url is like mydomain.com/category/mypage.html, Domain name should return mydomain.com Package URL provides a function parse() checks URL and returns URL instance. Hostname with URL instance return hostname.
Here is parse function syntax
func Parse(rawurl string) (*URL, error) 
It takes rawurl as input, returns URL instance an error object
package main

import (
 "fmt"
 "net/url"
)

func main() {
 urlInstance, error := url.Parse("https://mydomain.com/category/mypage.html")
 if error != nil {
  fmt.Println(error)
 }
 fmt.Println(urlInstance.Hostname())
}
Output is

mydomain.com

How to get Fully Qualified Domain Name - FQDN of a local machine 

There is no direct library to get FQDN of a machine. There is a custom wrapper library https://github.com/Showmax/go-fqdn based on OS and net package First install this library using below command go get github.com/Showmax/go-fqdn Following program returns fully qualified domain name if fqdn exists, else return unknown
package main

import (
 "fmt"

 fqdn "github.com/Showmax/go-fqdn"
)

func main() {
 fmt.Println(fqdn.Get())
}
Output is
DESKTOP-968A6TP

How to get the local IP address of a system 

the net package provides Dial function which connects to the target address of named network. UDP is a protocol which doesn't require a physical connection like TCP and target will not connect it
package main

import (
 "fmt"
 "net"
)

func main() {
 conn, error := net.Dial("udp", "8.8.8.8:80")
 if error != nil {
  fmt.Println(error)

 }

 defer conn.Close()
 ipAddress := conn.LocalAddr().(*net.UDPAddr)
 fmt.Println(ipAddress)
}
Output is
192.168.1.102:49703

Saturday, December 1, 2018

Learn Go Language with fundamental tutorials with examples

Friday, November 30, 2018

Learn Golang Tutorials - Rune Types Explained with examples

Golang Rune type introduction

Rune is a data type in the Go programming language. Rune is character literal which represents int32 value and each int value is mapped to Unicode code point https://en.wikipedia.org/wiki/Code_point

It represents any characters of any alphabet from any language in the world.
Each Character in language has a different meaning. For the English language, the character is from alphabets has 'B','b','&', for Chinese, it is '我'

Like other programming languages, Go don't have a character data type. bytes and rune are used to represent character literals. a byte represents ASCII codes,
rune represents Unicode characters encoded in UTF-8 format.

ASCII characters
It contains 128 characters which contain integer values from 0 to 127. It can be stored in 8 bit types ie byte

Unicode characters
It is a superset of ASCII character set which contains integer numbers in the range from 0 to 2 power 21 characters. Not all integers mapped to Unicode characters, but some are reserved.
Following are important points of Rune type 
  • It is an alias for int32, means It holds values  from o to 2 power 32 -1
  • Represents Unicode code point
  • It is a character literal enclosed in single quote 
  • Group of runes represents strings, can be cast to []rune
  • Rune represents character literal. 
  • rune is a keyword in go language

Rune type variable creation

You can create a variable like any other data type
var runeVariable rune // filled with default zero value -  U+0000
if the variable is declared without assigned any value, default compiler filled with default zero value ie U+0000
var runeVariable rune = 'Z'
On a single statement, the variable is declared and assigned with character literal value. Please note that character literals always enclosed in a single quote or without rune keyword, you can declare a variable and assigns a literal, a compiler will infer type as a rune. So default type is rune for a character.
var charVariable = 'C' // compiler infer its type as rune for character literals
Like any other variable assignment, you can use shorthand assignment operator ():= by omitting var keyword and rune keyword
runeVariable := 'Z'
compiler infer the type from the right-hand value

Create Rune type using Rune Literal values 

Rune literals are used to represent Unicode characters or single characters Unicode characters always start with \U followed by 4 digit hexadecimal values which can be represented in single character enclosed in double quotes or Unicode codepoints some of the examples of rune literals
var v1='B' is same as   '\u0042'
var v2 = '\u2665' same as '♥'
var letter = '\n' is same as '\u000A'
Unicode codepoints These will be mapped to characters which contain integer numbers. These numbers are called code points. Each Unicode has formats for code points. It always starts with U+ and followed by a hexadecimal value of the code point
var charVariable = 'C' // Type inferred as `rune` (Default type for character values)
var myvariable rune = '♥'

rune usage Examples

Check rune variable type 

rune is an alias for int32 for representing Unicode character. reflect.TypeOf function cheks rune variable type and return int32


package main

import (
 "fmt"
 "reflect"
)

func main() {
 variable := 'A'
 fmt.Printf("%d \n", variable)
 fmt.Println(reflect.TypeOf(variable))
}
The output of the above program is


65
int32

Iterate over a string over runes 

The string contains a slice of characters or runes. We can use range form of for loop to iterate the rune
func main() {

str1 := "kiran"
 for i, rune := range str1 {
  fmt.Printf("%d: %c:%U\n", i, rune, rune)
 }
}
When the above code is compiled and executed, the output is as follows
0: k:U+006B
1: i:U+0069
2: r:U+0072
3: a:U+0061
4: n:U+006E

Check Unicode code point and a number of a character or string

the string is represented in form of a group of characters ie array of runes. range form of for loop iterates each rune value and print character, integer value and the Unicode literal following is a program to get Unicode of a character or string
func main() {

 // input is string
 str := "my♥"
 for _, r := range str {
  fmt.Printf("%c - %d - %U\n", r, r, r) // character - integer - unicode
 }
 // input is character ie rune
 char := '♥'
 fmt.Printf("%c - %d - %U\n", char, char, char)

}
Output of the above program is

m - 109 - U+006D
y - 121 - U+0079
♥ - 9829 - U+2665
♥ - 9829 - U+2665
Convert String to/from rune array or slices When the string is converted to rune array, a new array is returned which each element contains Unicode code points. if any character in a string contains an invalid UTF-8 value, it returns 0xFFFD for it Here is a code program string to rune array/slice type with example
package main

import (
 "fmt"
)

func main() {

  strVariable := "my♥"
 runeArray := []rune(strVariable)
 fmt.Printf("%v\n", runeArray) // Ascii code array
 fmt.Printf("%U\n", runeArray) // unicode code point array

}
The output of the above program is
[109 121 9829]
[U+006D U+0079 U+2665]
when you convert rune array to string, all the Unicode codepoints in the array are converted and appended to a new string encoded in UTF-8 format if any Unicode is out of range of valid Unicode, It returns \uFFFD and symbol is � returned here is code program example for converting rune array to string
package main

import (
 "fmt"
)
func main() {
 runeArray := []rune{'\u006D', '\u0079', '\u2665',-1}
 str := string(runeArray)
 fmt.Println(str) // my♥�

}
output is
my♥�

How to get the length of a string in runes and bytes

The below program get the length of the string in bytes and lenght o f string in runes. for getting the length of runes,unicode/utf8 is used.RuneCountInString() function accepts string return integer value length of a string
package main

import (
 "fmt"
 "unicode/utf8"
)
func main() {
 str := "This is test string"
 fmt.Println(len(str))                    // return the length in bytes
 fmt.Println(utf8.RuneCountInString(str)) // return the length in runes

}
Output is
19
19