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.


Do you support us?

Business address
0x1D24D8f27ea73ff604C7685246bdC6ae55bddaEF

Is it language unites or divides the nation

  One way to connect with the heart of the nation: a shared language. Caesar took an oath in the senate... but was it fact or just a clever ...

Achieves