Thursday, June 27, 2019

Compose complex types

Welcome everybody, I'm happy after reading comments which you post on subreddits. Thankyou. Today, i will write my article on compose complex types but in end i give you a simple task, can you do that?

Types:
     In golang we create types in two ways
      1.       type-keyword  name-keyword  datatype
               type                Meter           float64
      2.     by using struct which you are familiar about.

   Let's start with simple example, so that we can understand how to do that.

Problem: I have two CEO, one CEO is elon musk and other is mark zuckerberg. Both CEO are also person and own attributes such as name or company. 
   If you know Object oriented approach you might think like this person is the person class and ceo is derived class. However this is not pure object oriented language, so that is not a solution. How can i solve? 
Oh Yeah, I build a struct type person, that hold all the attributes which person have. But the question what i do with ceo?
 I hope you know embed struct and anonymous structs concepts if, yes then problem solve. If you don't know then i will teach you with example
          type person struct{
                      name string
          }
          type ceo struct {
              p  Person  // embed struct
          }
      If you write another struct in which first struct parameter is the part of second struct then it's embed struct. 
           type person struct{
                      name string
          }
          type ceo struct {
              Person  // anonymous struct
          }
    Without parameter ceo struct called anonymous strut.
<Code/>
               package main

                 import (
               "fmt"
                )
         
              type Person struct{
        name string
       company_own string
        }
       type CEO struct{
   Person
      }
      var ceo CEO

      func(c *CEO)Description(){
  switch c.name {
case "Elon":
   fmt.Println("Name:",c.name,"\t","Company:",c.company_own,"\t","He is an                                innovator ")
break;
case "Mark":
   fmt.Println("Name:",c.name,"\t","Company:",c.company_own,"\t","He work                                 on social media ")
break;

}
    }
func main() {

c := &ceo
c.name = "Elon"
c.company_own = "Tesla, SpaceX"
c.Description()

owner:= CEO{Person{"Mark","Facebook"}}
owner.Description()
}
If you are checkout how this program work Hola
         This is very useful at package level variables , which i discuss upcoming articles. 
Question : You can do this example by pointers. Thankyou, have a great day

Wednesday, June 19, 2019

Do I, receiver, nil argument?

Hello,  Welcome back. This is quite interesting topic. Do I pass nil argument? The answer is yes. But How?

Nil Arguments?
         Here is my code </>     
package mainimport ( "fmt") type List struct{ data int tail *List } var list List func(r *List)Insert()( *List) { if r == nil{ panic ("Empty List") } return r }func main() { var l *List = &list l.data = 3 l.tail = nil p := l.Insert() fmt.Printf("%p", p) fmt.Println(p.data) h  := &list h.data = 1 h.tail = p c := h.Insert() fmt.Println(c.data, c.tail)}
         If you want to check either your data structure it is empty or full. The above example show a demonstration, how the nil arguments pass or receive by methods. I want to create my own list for this example.  
   If , you want to curious then you can Run this code. Thankyou, Have a great day.

Sunday, June 16, 2019

Methods Receiver as a reference


Hello, Welcome back; Today , we create new type of method receiver. When a function receive a value type parameter, on heap it will create copies of all the parameters, you pass. To avoid this problem, function receive reference type variable. Such as pointer, channels. Pointers have following advantages over variable. It Directly access, no copy , change in original value.

          Method Receiver Pointer:
            If you can write a code in C. Then you know, methods are not inherit C or Java Language. It's inherit from unix messages. 
                     func (c *Cal) Sum(y int) int{ // code }
            Cases :
       There're following cases that are exit 
1. If a method receiver and method argument both are T or *T type , it directly access.
2. If a method receiver is T type, however method argument as *T type. then  it need reference to access (&)
3. If a method receiver have *T and method argument as T type then dereference (*).

package main
import (
"fmt"
)
type Cal struct{
y int
}
func(c *Cal)Sum(y int) int{
return c.y -y
}
func main() {
// case 1
rec := Cal{3}
res := rec.Sum(2)
fmt.Println(res)
// case 2
r := Cal{4}
re := &r
fmt.Println(re.Sum(2))
//case 3
rc := Cal{5}
fmt.Println((&rc).Sum(2))
} 
 If you want to checkout the output, goto play link. If you remember my previous article it indirectly access and then set values, but in this example you only access via through pointers and also it's good approach. I hope you enjoy and learn more. Please share with your friends. Have a great day.
                        

Thursday, June 13, 2019

Object Oriented paradigm and golang

Welcome back , I hope you enjoy previous article. If you write a code before most of us in academics or enterprizes follow object oriented paradigm. In Java, c# and other languages "class" keyword represent this is an object oriented paradigm. But in golang there is no class keyword exist. "Is Oop Exist?" Generally speaking golang is not object oriented language, however it support oop at some extend. You will see just in a moment.

Methods Working :
First of all in oop there is class who have methods and properties. Methods are used to set properties. If you want to access class you have a reference of our class. Perhaps, in golang oop is little bit different. In go, you have a method or a reference of a struct. Now the question what is method?

Method is just like function, but it has one additional parameter called receiver, which is the same type of struct. Methods usually are fast and efficient. Methods give you direct access to structs reference. 
                             func (res Result) Add(x, y)


What is the receiver? 
          A receiver is an additional parameter that directly access structs fields and apply operation on it. Receiver concept inherit from old oop paradigm. 

package main
import (
"fmt"
)
type Result struct {
y int
}
var res Result
func main() {
res.Add(2, 4)
}
func (res Result) Add(x, y int) {
res.y = y
fmt.Println(x + res.y)
}
                                         Oreo-Time
                                                                                                    Have a great day.



       

Panic is an art




Writing a good program



 Panic Joke
Hello, guys after a long time, I'm a writing my next blog called panic is an art. 
I will start in a moment. But First we revise our knowledge, it is mandatory for this article. 

Defer: As you know defer means free your resources or clean your memory before quite. You already know defer statement  will change program execution. Defer statement work in LIFO order. Multiple defer functions call gorounties. Goroutines are different from normal flow, it's look similar jump command in assembly language. I will show you how to play with goroutines.

Panic: Panic is a built-in function, provide by golang language. Panic is just like exceptions, however exception concepts are not using in golang. Panic is very useful in debugging. 
panic(error). Panic is also very useful when rare condition maybe or may not be possible. Panic and defer follow side by side. If you crash your program, compiler tell 
                  func g()    // error in line 3 etc
                  func f()
                  func main()

Recover:   If you want to solve exceptions in java or c++, you familiar about try catch block. Here in golang, recover is to regain normal flow of program, after crash or panic state. 
                                  if r := recover(); r != nil{ // code }
                
Code</>:

package main
import (
"fmt"
)
func main() {
f(4)
}

func f(n int)(){
for ; n != -1; n-- {
fmt.Println(n)
}
if n == -1{
fmt.Println("panic")
  panicState(n)
}
}
func panicState(n int){
defer func(){
if p := recover(); p!= nil{
fmt.Println(p)
}
fmt.Println("normal execution end")
}()
g(n)
}
func g(n int){
for i :=0; i < 5; i++{
n+=1
fmt.Println(n)
}
}


package main
import (
"fmt"
)
type Person struct{
name string
}
func main() {
var stds Person
var name string = "ali"
s := handle(&stds)
(*s).name = name
fmt.Println((*s).name)
}
func handle(std *Person)(*Person){
defer func(){
if t := recover(); t != nil {
fmt.Println("recovering")
panic(t)
}
}()
return std
}

Have a great day.


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.
                 


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