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
  

No comments:

Post a Comment

Do you support us?

Business address
0x1D24D8f27ea73ff604C7685246bdC6ae55bddaEF

Mighty Roman Empire's trail and err

  The Roman Empire's strength, fuel by economical corridor and best men's for the service but Golden days might be over when corrup...

Achieves