Tuesday, May 21, 2019

Who's am I?

When we are writing problem or build a project, most of time we need to free our resources. When the program release resources ;
1. Program run so fast
2.  Resources allocate to others user too.
3. Handle multitasking.

Today I'm writing on Defer function call. Defer function call execute when you free your resources such as closing file, resources lock and unlock, network connection close etc.
Defer also use for debugging purpose too. Defer keyword is used.

func title(url string) error { 
resp, err := http.Get(url) 
if err != nil { 
    return err 
} 
defer resp.Body.Close() 
ct := resp.Header.Get("Content-Type") 
if ct != "text/html" && !strings.HasPrefix(ct, "text/html;") { 
   return fmt.Errorf("%s has type %s, not text/html", url, ct) 
} 
doc, err := html.Parse(resp.Body) 
if err != nil { 
   return fmt.Errorf("parsing %s as HTML: %v", url, err) } // ...print doc's title element... return nil 
}
  How Program Work?
      resp, err := http.Get(url) 
              Http.get take url and return error if there is. 
      defer resp.Body.Close()  here html resources release
      ct := resp.Header.Get("Content-Type")    get header of website
      if ct != "text/html" && !strings.HasPrefix(ct, "text/html;")  check either this html text.

Debugging using defer 
func bigSlowOperation() { defer trace("bigSlowOperation")() // don't forget the extra parentheses // ...lots of work... time.Sleep(10 * time.Second) // simulate slow operation by sleeping 
}func trace(msg string) func() { start := time.Now() log.Printf("enter %s", msg) return func() { log.Printf("exit %s (%s)", msg, time.Since(start)) } }
Output: 
           2015/11/18 09:53:26 enter bigSlowOperation 
           2015/11/18 09:53:36 exit bigSlowOperation (10.000589217s) 

Defer function call is very useful. 
Every time you don't reinitialize your resources before it use.
Once you initialize your resources, after job done you can defer your resources.
Defer execution just like stack up to bottom. 
package main

import (
"fmt"
)
func main() {
fmt.Print("Execution start\n")
Print()
f()
}
func Print(){
for i := 0; i < 5; i++{
fmt.Println("i:", i)
}
}
func f(){
for i := 0; i < 5; i++{
defer fmt.Println("i:", i)
}
}
                                                PlayTime
  

Sunday, May 19, 2019

Without this Agent , mission doesn't accomplish?

If you play military games such as Delta force , IGI Project , commandos etc . You familiar about in your team. Each member of team are unique in their skills. Some are snipers , short gun , hackers, communication officer. Now I will introduce golang special agent which are quite helpful in most of time.

              Variadic Function will show in a moment!
Variadic Function:
           Variadic  Functions means a function that arguments varing. In variadic function ... called ellipsis.  
package main
import (
"fmt"
)
func main() {
values := []int{1,2,3}
fmt.Println("Value[0]",seriesAdd(values[0]))
fmt.Println("Total", seriesAdd(values...))
}
func seriesAdd(x ...int)int{
var count int = 0
for _, v := range x{
count+= v
}
return count
}
Conditions :
    Before passing to the variadic function array must be slice.
                  values := []int{1,2,3} // slice
    Always use ellipsis in, when array pass as a argument.  
Working of Program:
         When i'm passing a single value (values[0]) then it only return single variable. But when i'm passing array as an argument. This function return sum of array. This function work according to my requirement.
Observations:
         In main function last line 
                      fmt.Println("Total", seriesAdd(values...))
               That pass entire array  to the function
         fmt.Println("Total", seriesAdd(values)) // error receive
        In seriesAdd(x ...int) you observe I'm using ellipsis, that take array as a parameter
Now you can play with your special agent. I hope you enjoy              
            
       


Thursday, May 16, 2019

Anonymous Caller Function

You can know about function values but this article also link with my previous blog. Let's start with "Anonymous Caller Function"

package main
import (
"fmt"
)
func squares() func() int {
var x int
return func() int {
x++
return x * x
}
}
func main() {
f := squares()
fmt.Println(f()) // "1"
fmt.Println(f()) // "4"
fmt.Println(f()) // "9"
fmt.Println(f()) // "16"
}  
What we already Know ?
This code confuse you, don't worry let's start what we already know about functions. 
 func squares() int{ return x *x}. This function return square which we pass as argument.
 f := squares() function definition receive by f for further processing.
What we don't know?
func squares() func() int {
var x int
return func() int {
x++
return x * x
}
}
            1. func() int: this is an anonymous function. Anonymous function are those functions which is similar like inner function, but without name. 
           2. return func() int: this function inside square function. Anonymous function use local variables, which are already declare in square function. Return fun() int tells that compiler anonymous function value. Again this is a function so, we can like function except before function return keyword use. Actually Function B take Function A as a input and after processing it return as a output of Function AB. That's why confuse so many times.  

Recursion in Anonymous Function:
             var visitAll func(items []string)
              visitAll = func(items []string) {}
 Recursion in Anonymous function in two steps.
        1. declare a variable along with function definition 
        2. initialize variable with function which to be recursive


func topoSort(m map[string][]string) []string { 
var order []string seen := make(map[string]bool) 
var visitAll func(items []string)
         visitAll = func(items []string) { 
                                   for _, item := range items { 
                                        if !seen[i tem] { seen[item] = true 
                                                visitAll(m[item]) 
                                          order = append(order, item) } 
                                       } 
                                  } 
             var keys []string 
            for key := range m { 
                      keys = append(keys, key)
             }
             sort.Strings(keys)
             visitAll(keys) return order 
            }  
Warning:
If you don't follow these steps these, then program will not execute.

Tuesday, May 14, 2019

How Function values are useful?

Golang is interesting language. If you wanna to play then start build your lego empire today. You know how to build homes, shops, trees etc. Someday, I will show you how to build a factories or companies so that our universe look like a real world. 

Like ordinary values assign to variables, in golang you can assign function values to your variables, because function values have own type.

package main
import (
"fmt"
)
func main() {
f:= square
fmt.Println(f(2))
f = underRoot
fmt.Println(f(4))
f = add
fmt.Println(f(2,2)) // error
}
func square(x int)int {
return x * x
}
func underRoot(x int)int {
return x*1/2
}
func add(x, y int)int {
return x+y
}
       Confused ?
               f = underRoot
               f = add // error
Are you confuse in these statement, if yes then square initially assign to f, which take one parameter as a argument. This tells f(2) that f hold square definition and 2 in our case value.
            4 [Ok , everything fine]
when underRoot assign to f. According to f definition , it take only one parameter as argument, which is again okay. But when add assign to f, now the compiler again check the definition of add function and compare with existing definition. In this case now whole
definition change which is not allowed. That why it produce error.

Warning :
Never return nil type value otherwise you received panic. You can't compare function values with other function value, function values are not used keys in maps.

You can also compare function value with nil. That Okay 
  

Monday, May 13, 2019

Good Errors Need Your Help

I assume that you have write a program in another language before learning golang. Like c plus plus , Java etc. When a compiler produce exception you can handle it by yourself. In this article i only show you a good errors.

package main
import (
"fmt"
"errors"
)
func main() {
div, err := divide(0,3)
if err != nil{
fmt.Println(div)
}
fmt.Println(div,err)
}
func divide(x , y int )(int, error){
if x == 0 {
return x/y , nil
}
return x/y, errors.New("PASS")
}
If you observe in my above example you see if x equal to zero then it send error while when x not equal to 0 then it send me "Pass" ? errors.New take a string a argument as a parameter and in case any error. This is very productive function when you're working on huge project.
Bad Errors also exit in golang but that will come on right time. Programmer handle bad errors like Java developers handle exceptions.

Sunday, May 12, 2019

Optimize your function

Everyone want to improve his skills. Programmer usually clean their code after month or when he/she is available. Clean Code means change in existing code that work faster then before and resolve issues which he face before. Within a moment, I will show how to do that?

             If you remember when i write a tic toc game  in golang. That time i explain you functions take only one parameters. Actually that time i don't know how to pass multiple arguments. 
                      func add(x,y int)int{ /* add functionality*/}

                      func move (key string , y  int ) { /**/}
In case "a" you observe x, y are two parameters and common data type. When we're in school, we study operation add only available for numbers. While in case "b" move function take two parameters both are different. 
Multiple Value Return:
In Golang you're function return so many values at ones. 
           
          func moveCheck(x,y int ){                      if x != 0 && y != 0 && x < 3 && y < 3 {                               return x ,y                        }                  return -1,-1          }          func main(){                   validX,validY = moveCheck(2,1)
                           fmt.Println(validX,validY) 
          }
    Baren Return:
This is the new concept which only introduce by Golang, this type of return increase the efficiency of code .
                    
package main
import (
"fmt"
)
func main() {
fmt.Println(f(3))
}
func f(z int)(x int){
x = z
return
} Output: 3

Function f take a single parameter as a argument and
return a single return value. One thing you observe in
return statement return keyword doesn't take any
expression or operator then how it return whatever we
pass as a argument? The answer of this question is
simple in function return x and z value assign to x
variable . At the time of function declaration
programmer already tell that it return x value. When a compiler read return statement it check function declaration variable and return value of that variable. This is called barren return.
                 


Thursday, May 2, 2019

How to take care naughty functions -> "Recursive"

When we play Recursive Function, we need precautions , because it's recursive in nature. There's a big problem if base condition not valid then it repeat infinite times. Which cause panic in go-lang. Today, I use simple example such as factorial 

package main
import (
"fmt"
)
func main() {
i := fact(5)
fmt.Println(i)
}
func fact(n int)int {
if n == 1{
return n
}
return n * fact(n-1) Play 
If you're a detective then you may notice that in func fact return again fact. This line
actually recursive line which repeat over and over, until base condition are true
  

Wednesday, April 24, 2019

Agents ready to Go on a mission

I refer function as a agents because function work like agents. Sometime different programmer, working on single project or it can be poor choice whole application written in main. That why every language introduce packages and functions.

Packages will be beneficial when programmer use predefined functionalities which already provided by different programmers . Such as images, net packages. If you explore you know images contain , functions, constants, variables and subdirectories. This package only concern with images or pixels. 

Functions are the good option when a programmer work on modules or a blocks or even above scenario. If you play a military games then you know on a mission there are so many agents work together to accomplish mission. Each agent have own tools. Each person have different skills such as some agents short range shooter or some agents have long sniper, some agents are experts in technology etc. You can create any type of function. We build so many functions.

How Functions Work?
Function need a value or values as a argument along with type. Some functions return value after operation or some function return nothing.   
                            func p(x int) {     // print x }
                            func q (x int, y int) int { return x-y}
              
 Pass by Value and Pass by Reference 
            Pass by value:
                  p and q both function called pass by value. In Pass by value copy of variables pass as arguments, that's why change on value doesn't affect on original variables. Functions & variables both are initialize on lexical block. 
           Pass by reference:
                         functions which take pointers, maps, slice , channels as arguments called pass by reference. It can affect on original value after modification.

Functions Writing Ways:
                         func p (x int) int{} 
                         func p (_ int) int{}
                         func p (x int) (int){}
                         func p (x int) (x int){}
Working with other language
                       You can also write like 
                                                     func p (x int) int 
                        this is way to compiler on different language.


Thursday, April 18, 2019

Go handle Json Perfectly

JSON abbreviation "JavaScript Object Notation". There're so many tools for structure data such as xml, Json, asn.1 and google protobuf.

XML and JSON:
writing code in a xml, so called boilerplate. Java and android use xml for project management. While json, is easy as compare to xml. Mostly use json because it's easy to play around and good choice for web application.

Code :
package main
import ( "fmt" "encoding/json")
type Books struct{ Title string  Status bool Writer string  Comments string}


func main() { var Library =[]Books{ {Title:"Lord of Rings the fellowship", Status:false, Writer:"J-J-R-Tolkien",Comments:""}, {Title:"Quantum Aspects of Life",Status: false, Writer:"Paul-C",Comments:""}, {Title:"You were born rich", Status:true, Writer:"Bob Proctor",Comments:"good book"}, } if lib , err := json.MarshalIndent(&Library,""," "); err== nil{ fmt.Printf("%s",lib) } }
Encode library provide so many sub packages json one of them, try to use it the above it just show you a demonstration. You can use Marshal or MarshalIndent for encoding your data in json.

Marshal and MarshalIndent:
  Marshal :
            lib,err := json.Marshal(Library)
        Marshal take a parameter that to be convert in my case that is Library. Json.Marshal
return value and error so you can handle it. This function have one problem encoded data are  not distinguishable. Return value similar to string. 

MarshalIndent:
           lib, err := json.MarshalIndent(&Library, "", " ")
 Again this is similar to previous function but , this function demand address of data , not itself. Second it take two parameters . Just play around

Similar like encoding, you can also decode data by using unMarshal and unMarshalIndent.

I'm thinking i will add google protobuf in my upcoming articles.

 



                                                                              



Tuesday, April 16, 2019

How to Optimize our code efficiency.

In Golang structs are very powerful and common use. In previous article, I show you how to write a struct but this is not efficient way to write. 

type Point struct{ X,Y int }

point := Point{1,2}
                code.1.1 


There are two types struct literals :
                In first type, study above code. Programmer usually avoid this because it's difficult to remember about fields, it's should be in right order. Programmer use this in custom packages and smaller structs types.

                 In second type Programmer like very much , it's more powerful then previous type.
                 anim := GIF.gif{loopCount: nframes}
               
                 If any field value omit then that case value initialize with zero. Structs can also pass by reference [Pointers]. As you know, passing structs as a parameters with the help of pointers. Pointers create copy and use particular copy .

Structs Literals access through pointer.
                     p := &Point{1,2}
                      p := new (Point)
                      *p = Point{1,2}

Structs Comparable 
                 We can also compare structs . "==" & "!=" are common operators for comparison. Structs can also comparable with other types , in that case maps are very helpful.

Embed Field and Anonymous :

      Embed Field :
                  
package main
import ("fmt")
type Point struct{
X,Y int
}
type Circle struct{
Center Point // embed structs-1
Radius int
}
type Wheel struct{
Circle Circle //embed structs-2
Spokes int
}
func main(){
var w Wheel
w.Circle.Center.X =2
w.Circle.Center.Y =2
w.Circle.Radius =3
w.Spokes =3
fmt.Println(w)
} In embed field we can create a structure of any type that structure is the field of next struct. In Wheel or circle you can see this. Anonymous Field: type Circle struct { Point Radius int } type Wheel struct { Circle Spokes int } var w Wheel w.X = 8 // equivalent to w.Circle.Point.X = 8 w.Y = 8 // equivalent to w.Circle.Point.Y = 8 w.Radius = 5 // equivalent to w.Circle.Radius = 5 w.Spokes = 20 Anonymous Field similar like embed field but there 's a great difference. In anonymous field, field have a type but field don't have any name. That's why we called them anonymous field.
package main
import ("fmt")
type Point struct{
X,Y int
}
type Circle struct{
Point //anonymous case#1
Radius int
}
type Wheel struct{
Circle //anonymous case#2
Spokes int
}
func main(){
var wheel Wheel
wheel.Circle.Point.X =4
wheel.Circle.Point.Y =4
wheel.Circle.Radius =4
wheel.Spokes =4
fmt.Println(wheel)
w:= Wheel{Circle{Point{4,4},3},2}
fmt.Printf("%v",w)
}
Because ‘‘anonymous’’ fields do have implicit names, you can’t have two anonymous fields of the same type since their names would conflict. And because the name of the field is implicitly determined by its type, so too is the visibility of the field. You can follow any convention, which you like. This is just a example, upcoming articles . I will discuss you, Why Composition is so important?


           

                   
                   

Do you support us?

Business address
0x1D24D8f27ea73ff604C7685246bdC6ae55bddaEF

Kings archives to book stalls 📚

  Through books, we can explore the past, understand the present, and shape the future. Historically, books were treasured by kings and merc...

Achieves