Friday, October 16, 2015

Concurrency Parallelism and Goroutines for Beginners

In the world around us many un/planned activities/events simultaneously and often independent of each other.  While reading this, you may receive a phone call and while still on the call you might receive  a few push notifications on your mobile from Facebook or WhatsApp. While reading this and attending to that phone call, you might be listening to your favorite number played in your home theater and you may reach out to adjust the volume level. Does this make sense or you're still scratching your head... yet another activity! 

Yes, the world is indeed parallel. Apart from everything else even in technology world also the concept of parallelism can be observed viz. Multicore machines, networks, clouds of CPUs, Users request to a web server - all are parallel.

That's probably the reason we get stuck at times when we try to solve a real world problem using the non parallel approach (read Object Oriented techniques).

Almost a decade back the following was one of the pet interview questions thrown mostly to any developer with 3+ years of experience:
  •  Have you implemented multi-threading in x language? 
Where x = C#, Java or any other language that supports multi-threading.

Without any doubt, I agree (like most of us) that multi-threading is complex and a beast too big to be tamed by mere mortals with average intelligence. You can agree to disagree with me and may call this a common fallacy :-)
  • Goroutines has made concurrency / multi-threading easier to use.
If you already understand the basics move on to Go Channels

What is Concurrency?

Concurrent = happening, or done at the same time

Concurrency is a way to structure a program by breaking it into pieces that can be executed independently.

The Go tools of concurrency make it almost trivial to build a safe, working, scalable & parallel design.

Here, Processes in the general sense, not Windows/Linux processes.

Is Concurrency same as Parallelism?

No. They are not same, but are related.

Rob Pike says:
  • Concurrency is about dealing with lots of things at once.
  • Parallelism is about doing lots of things at once.
  • Concurrency is about structure, parallelism is about execution.
  • Concurrency provides a way to structure a solution to solve a problem that may (but not necessarily) be parallelizable.
Here's an excellent video by none other than one of the creators of Go - Rob Pike Concurrency Is Not Parallelism

Go tools to Implement Concurrency
  • Goroutines - concurrent execution.
  • Channels - synchronization and messaging.
  • Select - multi-way concurrent control.
What is Goroutine?

A goroutine is a function running independently in the same address space as other goroutines. They're a bit like threads, but they're much cheaper.

A goroutine is a lightweight thread of execution. It's routine to create thousands of goroutines in one program. Stacks start small, but grow and shrink as required.
Goroutines aren't free, but they're very cheap.

Important Update: To synchronize concurrently running functions Go provides Channels.

The following code sample uses time.Sleep() to sync the goroutines - bad programming practice and should be avoided. Synchronizing your goroutines like this can introduce several serious bugs in your code. The purpose of this code sample is to give you a feel of goroutines in action.

Example Code

Play with the code


package main

import (
 "fmt"
 "time"
)

func Tortoise() {

 time.Sleep(5 * 1e9)
 fmt.Println("Tortoise is still somewhere near the Starting Line.")
 time.Sleep(10 * 1e9)
 fmt.Println("Tortoise reaches 10 miles after 10 sec.")
 time.Sleep(10 * 1e9)
 fmt.Println("Tortoise reaches 20 miles after 20 sec.")
 time.Sleep(6 * 1e9)
 fmt.Println("Surprise... Tortoise reaches finish line! Completes 26 miles in 26 sec")
}

func Rabbit() {
time.Sleep(2 * 1e9)
 fmt.Println("Rabbit reaches 10 miles after 2 sec.")
 time.Sleep(4 * 1e9)
 fmt.Println("Rabbit reaches 20 miles after 4 sec.")
 time.Sleep(7 * 1e9)
 fmt.Println("Rabbit takes power nap.")
 time.Sleep(20 * 1e9)
 fmt.Println("Rabbit reaches the finishing line! OOOPs Rabbit lost the race!")
}

func main() {

 fmt.Println("Marathon Race - 26 miles, Tortoise vs. Rabbit.")
 fmt.Println("On your mark. Starting pistol fired...")
 fmt.Println("The Rabbit sprints ahead while the Tortoise is dead slow.")
 go Rabbit()
 go Tortoise()
 time.Sleep(34 * 1e9)
 fmt.Println("Keep GO-ing :-) even if you're slow.")
}


Output

Marathon Race - 26 miles, Tortoise vs. Rabbit.
On your mark. Starting pistol fired...
The Rabbit sprints ahead while the Tortoise is dead slow.
Rabbit reaches 10 miles after 2 sec.
Tortoise is still somewhere near the Starting Line.
Rabbit reaches 20 miles after 4 sec.
Rabbit takes power nap.
Tortoise reaches 10 miles after 10 sec.
Tortoise reaches 20 miles after 20 sec.
Surprise... Tortoise reaches finish line! Completes 26 miles in 26 sec
Rabbit reaches the finishing line! OOOPs Rabbit lost the race!
Keep GO-ing :-) even if you're slow

A Brief Description of Above Code

time.Sleep(5 * 1e9)


In above code we're introducing a time delay of 5 seconds. Replace 5 with 10 to get a delay of 10 seconds. Know more about Sleep function here.

Apart from the main() function there are other 2 functions namely Tortoise() and Rabbit().

In the main() function we've 2 goroutines namely go Rabbit() and go Tortoise().
From the output you can easily see how both the functions are getting executed concurrently.

Important: By default, Go code is NOT parallel i.e. only a single core or processor is dedicated to a Go-program, regardless of how many goroutines are started in it; so these goroutines are running concurrent, they are not running in parallel: only one goroutine is running at a time.


How can I improve this code? Please share your thoughts.

Monday, October 5, 2015

Go Interfaces for Absolute Beginners

The concept of Interfaces and its practical implementation may be rather daunting for beginners. It may require immense time and patience to assimilate the idea of interfaces.

Interfaces are an abstraction that helps you to achieve the following objectives with your code:

                  1. Clean & readable.
                  2. Scalable.

An interface defines a set of methods without any implementation code. So, an interface is simply an abstraction and can't contain any variables or code.


Declaration format of interfaces:

type Logger interface {
            method1 (param list) return type
            method1 (param list) return type
}

As per the official recommendation:
  • In the above format, Logger is the name of interface. It is idiomatic in Go to suffix the name of interface with er in most of the cases. There are exceptions but a common practice for naming an interface is: 
        • method name + er
  • Interfaces with one or two methods are common in Go code. More than three methods in an Interface is not considered idiomatic.
  • A type can implement multiple interfaces. Interface can be implemented by any type. But an interface can't implement itself.
  • Multiple types can implement the same interface.
  • Like many other languages, in Go also, we must implement all the methods in the interface.


Here's a code snippet (Code Ref# 1) that finds the area of a rectangle and triangle using functions. The same exercise is refactored in Code Ref#2 using structsmethods and interfaces.

Code Ref# 1. Play Here


package main

import "fmt"

func AreaRectangle(l, w int) int {

 return l * w
}

func AreaTriangle(b, h int) int {

 return (b * h) / 2 //Area of a triangle is (base*height)/2
}

func main() {

 fmt.Println("Area of Rectangle:", AreaRectangle(3, 4))
 fmt.Println("Area of Triangle:", AreaTriangle(5, 20))

}

Output

Area of Rectangle: 12
Area of Triangle: 50

Code Ref# 2. Play Here

package main

import "fmt"

type Rectangle struct {
 width, height int
}

type Triangle struct {
 base, height int
}
type Shaper interface {
 Area() int
}
// You must implement all the methods in the interface
func (s Rectangle) Area() int {
 return s.width * s.height
}
func (t Triangle) Area() int {
 return (t.base * t.height) / 2
}
// Variable declared as an interface type can call methods that are in the named interface.
// Generic 'measure' function that works on any Shape.

func measure(s Shaper) {
 fmt.Println(s)
 fmt.Println(s.Area())
}
func main() {
 s := Rectangle{width: 3, height: 4}
 t := Triangle{base: 5, height: 20}
// The Rectangle struct type implements the 'Shaper' interface so we can use instances 
// of these structs as arguments to measure.
 measure(s)
 measure(t)
}



Output



{3 4}
12
{5 20}
50
P.S. Interfaces are a bit difficult to understand. A beginner must persist with it, practice as many examples as possible to understand and assimilate the concept. I'll review this post every now and then and may add a few more code samples.


Thursday, September 24, 2015

Deploying Go on Google App Engine

Why GAE?

For the uninitiated, Google App Engine (GAE) is a PaaS (Platform as a Service). By deploying your app here, you get the following 2 immediate benefits:
      1. No servers for you to maintain.
      2. Easy to scale as your traffic & data storage needs change.
GAE is now a part of Google Cloud Platform. 

Google Cloud Platform is a set of modular cloud-based services that allow you to create anything from simple websites to complex applications.

Google Cloud Platform is build on the same infrastructure that allows Google to return billions of search results in milliseconds, serve 6 billion hours of YouTube video per month and provide storage for 425 million Gmail users!

Do You Want to See the Live Page that I Deployed on GAE?


Visit http://golangprogae.appspot.com/. This is a responsive page build on Bootstrap framework.


Getting Started with Go on GAE

Download and unzip the Go App Engine SDK

P.S. - Add App Engine Go SDK directory to your PATH environment. Also, Go requires Python 2.7x, Download it from here, if it's not already installed in your machine.
  1. Go to your working directory. Create a new project directory and name it anything you may like, I've named it gogae. 
  2. Inside this project directory, create a file named app.yaml
  3. Copy the following code and paste it to your app.yaml file. Remember, later on you've to edit the application name marked in red (golangprogaewith your own Project Id that you'll create in GAE interface at the end of this tutorial.
Info. - app.yaml contains GAE application configuration. In the above RefCode# 1, you can change the version. GAE has the ability to render different versions based on your preference, if you wish to go for A/B testing.

RefCode# 1


# This is a comment
# application is mandatory (replace with your project Id)
application: golangprogae
# version is mandatory
version: 1
# runtime is mandatory
runtime: go
# api_version is mandatory
api_version: go1
# handlers is mandatory
handlers: 
- url: /.*
  script: _go_app

4. Create another file, name it whatever you like. I've named it as bootstrap.go

RefCode# 2


package gocloud

import (
 "fmt"
 "net/http"
 
)

func init() {
 http.HandleFunc("/", handler)
 
}

func handler(writer http.ResponseWriter, request *http.Request) {
 
 fmt.Fprint(writer, "<!DOCTYPE html><html><head><title>Go web app on GAE</title><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'><script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script><script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js'></script></head><body><div class='container'><div class='jumbotron'><h1>Go App on GAE</h1><p>Resize this responsive page to see the effect of Bootstrap! For details <a href='http://www.golangpro.com'>visit GolangPro</a></p> </div><div class='row'><div class='col-sm-4'><h3>Why Go?</h3><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p><p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p></div><div class='col-sm-4'><h3>Why GAE?</h3><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p><p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p></div><div class='col-sm-4'><h3>Why Bootstrap?</h3><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p><p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p></div></div></div></body></html>" )
 
}

Deploy to your Local Machine [Development Server]

I'm using a windows machine.


In command prompt navigate to the project directory (gogae) that you created a little while ago in the beginning of this tutorial. Once you're inside the project directory use the following command to deploy it locally:

goapp serve

Once you successfully execute the above command open the following to see the result:

http://localhost:8080/

The Development Server will display the web page that we just build using Go.

If you wish you can check the local Admin Server of GAE running for this app on your local machine. Open the following:

http://localhost:8000/

It looks like the following image:




How to Deploy to Google App Engine?

1. Log into Google Developer Console

For those who are yet to signup, at the time of writing this there's a $ 300 credit promo for FREE to try out Google Cloud Platform.

2.  Create a new project. Note down the Project Id. In my case the project Id is golangprogae


3. Open the file named app.yaml. You've to edit the project Id before deployment, see RefCode# 1 above (in the beginning of this article). Edit the name of the application marked in red and replace with your Project Id.

4. In command prompt navigate to the project directory (gogae) that you created a while ago. Once inside the project folder use the following command to deploy it to GAE:

goapp deploy


5. It hardly takes 5 seconds for this app to get deployed. Once it is completed visit <http://YOUR_PROJECT_ID.appspot.com>. In my case it's http://golangprogae.appspot.com/

How was it? How can I improve this? Please share your thoughts.

Friday, September 4, 2015

Embedded or Anonymous Fields in Structs

For an introduction to Structs read: Go Structs   


Go supports anonymous or embedded field - i.e. a field without a name but with a type. You can say that the type itself is a name.

Why Anonymous or Embedded Fields or Composition?


Yes, Embedded fields, Composition or Anonymous fields are different names for same concept.

If you're familiar with object oriented programming you can relate an anonymous or embedded field with Inheritance and its single biggest advantage is code re-usability. 

CodeRef# 1


package main

import "fmt"

type person struct {
 name   string
 gender string
 age    int
}

type employee struct {
 person //embedded field
 salary float64
 dept   string
}

func main() {
 empProfile := employee{person{"Jack", "M", 32}, 3000, "Electronics"}
 fmt.Println(empProfile)
 fmt.Printf("%s works in %s department. Salary: %.2f\n", empProfile.name, empProfile.dept, empProfile.salary)
}

Output

{{Jack M 32} 3000 Electronics}
Jack works in Electronics department. Salary: 3000.00

Play with the above code

CodeRef# 2


package main

import "fmt"

type person struct {
 name   string
 gender string
 age    int
}

type employee struct {
 person //embedded field
 salary float64
 dept   string
}

type manager struct {
 employee //embedded field
 numEmp int
}

func main() {
 empProfile := employee{person{"Jack", "M", 32}, 3000, "Electronics"}
 mgr := manager{employee{person{"Bill", "M", 55}, 5000, "CSc"},21}
 fmt.Printf("%s works in %s department. Salary: %.2f\n", empProfile.name, empProfile.dept, empProfile.salary)
 fmt.Printf("%s manages %s department with %d employees. Salary: %.2f", mgr.name, mgr.dept, mgr.numEmp, mgr.salary,)
}

Output
Jack works in Electronics department. Salary: 3000.00
Bill manages CSc department with 21 employees. Salary: 5000.00
Play with the code here
What Happens in Case of a Field with the Same Name in Two Structs?
For example see the following: 
A field named location exists in both the structs (person and employee). 
  • What happens when you call empProfile.location? 
  • Which location gets a precedence?
RefCode# 3
package main
import "fmt"

type person struct {
 name, gender, location  string
}

type employee struct {
 person //embedded field
 salary float64
 dept   string
 location string
}

func main() {
 empProfile := employee{person{"Jack", "M", "Chicago"}, 3000, "M", "New York"}
 fmt.Printf("%s. Current location: %s\n", empProfile.name, empProfile.location)
 fmt.Printf("%s. Native location: %s\n", empProfile.name, empProfile.person.location)
}

Jack. Current location: New York
Jack. Native location: Chicago
Play with the code here
As it is evident from the above output, the child field (i.e. the location from employee) takes precedence over the parent (i.e. person). In Object Oriented parlance this provides a way to override a field or method.
If you liked it, spread the word about it. Happy coding!

Sunday, August 30, 2015

Pass by Value vs. Pointers

When you call a function with parameters and pass an argument to it, Go by default pass the argument by copying it (i.e. pass by value). If you want to pass by reference use pointers. 

What does this mean?

For an Introduction to Pointers read Go Pointers

When an argument is passed by value, a function receiving a value will receive a copy of the original value and when you mutate (change) this value it will mutate the copy and not the original value. Let us see the following example:

Example RefCode# 1: Pass by Value

package main

import "fmt"

type Player struct {
 Name  string
 Score int
}

func currentScore(p Player) int {
 p.Score++
 return p.Score
}
func main() {
 arg := Player{Name: "Messi", Score: 101}
 fmt.Printf("%s just scored his %dth goal.\n", arg.Name, currentScore(arg))
 fmt.Printf("Now "+"%s has a total of %d goals.", arg.Name, arg.Score)
}

Output


Messi just scored his 102th goal.
Now Messi has a total of 101 goals.


Play with the above code

The intention of the above code is to show that Messi has just scored one more goal so total number of goals scored by him should become 101+1 i.e. 102. The second statement of the above code is wrong as it is still showing the old value (i.e. 101) in case of total number of goals scored! This has happened because we've changed the copy and not the original value!

See how the output differs when we pass the value by pointer instead of value. The following code shows the desired result:

Example RefCode# 2Pass by Pointer


package main

import "fmt"

type Player struct {
 Name  string
 Score int
}

func currentScore(p *Player) int {
 p.Score++
 return p.Score
}

func main() {
 arg := &Player{Name: "Messi", Score: 101}
 fmt.Printf("%s just scored his %dth goal.\n", arg.Name, currentScore(arg))
 fmt.Printf("Now "+"%s has a total of %d goals.", arg.Name, arg.Score)
}

Output
Messi just scored his 102th goal.
Now Messi has a total of 102 goals.

Play with the above code




What's the Difference Between RefCode# 1 & RefCode# 2?
The two code samples are same except the following 2 lines. Have a look and try to assimilate how pointer is used.

func currentScore(p Player) int {
vs.
func currentScore(p *Player) int {
----------------------------------------
arg := Player{Name: "Messi", Score: 101}
vs.
arg := &Player{Name: "Messi", Score: 101}
What are the Benefits of Pointers?

1. In contrast to the value type receiver, a pointer receiver is extremely lightweight (4 or 8 bytes) as only the pointer (a reference i.e. an address and not the actual value) is copied and not the entire value. 
2. you must use a pointer in cases where the argument value needs to be modified (like in the above example).
Official version from Go FAQs
I've copied and pasted it here for your reference [source]:
As in all languages in the C family, everything in Go is passed by value. That is, a function always gets a copy of the thing being passed, as if there were an assignment statement assigning the value to the parameter. For instance, passing an int value to a function makes a copy of the int, and passing a pointer value makes a copy of the pointer, but not the data it points to. Please share if you liked it.

Monday, August 17, 2015

Variadic - Functions with Variable Arguments

What are Variadic Functions?


A variadic function is one that can accept zero or more arguments for its last (or only) parameter. Such functions are indicated by placing an ellipsis (...) immediately before the type of the last or only parameter.

--Source: Programming in Go by Mark Summerfield.

Example: fmt.Println() is a variadic.


If you're a beginner, before you proceed, you can read my post about the Introduction of Functions in Go

An example is better than any explanation. See the following code sample and its output. In the code we've a function named classify that takes variable (arbitrary) number of string arguments (letters) and determines whether the letter is a vowel or consonant.

Note: Variadic functions receive the arguments as a slice of the type i.e. in below case it is string.


package main

import "fmt"

func classify(l ...string) {

 fmt.Println(l)

 for _, l := range l {

  switch l {

  case "A":
   fmt.Println("A vowel as in Apple")

  case "E":
   fmt.Println("E vowel as in Elephant")

  case "I":
   fmt.Println("I vowel as in Ice")

  case "O":
   fmt.Println("O vowel as in Ox")

  case "U":
   fmt.Println("U vowel as in Umbrella")

  case "Y":
   fmt.Println("Y as in Cry is a vowel. Y in Yellow is a consonant")

  default:
   fmt.Println(l + " consonant")

  }
 }

}

func main() {

 //Pass arbitrary number of string arguments
 classify("A", "B")
 classify("D", "E", "F")

       //Pass arbitrary number of arguments using Slices
 alphabet := []string{"A", "B", "C", "D", "E", "F", "G", "X", "Y", "Z"}
 alpha := alphabet[:2]

 classify(alpha...) //Note the way slice arg is passed using ...
 alphabet = alphabet[7:]
 classify(alphabet...)
}


Output





Please share if you liked this.

Sunday, August 16, 2015

Golang Interview Questions & Answers

These interview questions and answers are NOT intended to serve as a shortcut to intensive learning by self trying and assimilating the programming concepts of Go. Moreover, these questions are framed by me from my imagination while learning Go and not from any Go interview as such.

The sole purpose of these questions are to tickle your grey cells to make you think quickly and decisively in the right direction when you face challenges of daily rigors of Go programming. Also, for some of us, the Q and A format works well as far as learning is concerned, may be because in comparison to a  long paragraph, Q and A are specific in nature apart from being precise.  


Q# 1. Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. 


An image of the expected output is shown here (only till 20 and not 100 as expected)




A# 1. Read this post for Answer

2. How many Looping constructs are present in Go programming language?

A# 2. Only one loop - for.

Q# 3. What is the default value of type bool in Go?

A# 3. false.

Q# 4. In case of Constants which type of expressions are evaluated at compile time and which are evaluated at run time?

A# 4. As a rule Constants are evaluated (determined) at compile time and never at run time. 

Q# 5. Which one of the following is correct?

         a. const Pi = 3.14

         b. const Pi = math.Pi 
         c. both a and b are correct
         d. None of the above

A# 5. c


Q# 6. Short  variable declaration := can be used only inside a function. True or False?

A# 6. True.

Q# 7. Short declaration := can be used for defining global variables. True or False?

A# 7. False.

Q# 8. What's wrong with the following code?

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import "fmt"

func main() {

     var a int8 = 3

     var b int16 = 4

     sum := a + b
 
 fmt.Println(sum)
}


A# 8. Compile time error, you'll get the following message:
invalid operation: a + b (mismatched types int8 and int16)

Note - Though int8 and int16 are similar in nature they are two distinct types. One of the
 variables must be converted explicitly so that both the variables are of same type.

Q# 9. How can you rectify the above code?

A# 9. Replace line 11 with the following line.

          sum := a + int8(b)

Q# 10. What's the output of following code?

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package main

import "fmt"
 const ( 
       i = iota
       j 
       k 
 )
func main() {
 fmt.Println(i, j, k)
}

A# 10.

0 1 2
Q# 11. What's the output of following code?

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package main

import "fmt"
 const ( 
       i = 7
       j 
       k 
 )
func main() {
 fmt.Println(i, j, k)
}
A# 11
7 7 7
Q# 12. Refer code snippet Ref12A and Ref12B. They have the same output. True or False?

Ref12A:
package main

import "fmt"

const(
    p = iota  
    q = iota  
    r = iota        
)

func main() {
    fmt.Println(p, q, r)
}
Ref12B
package main

import "fmt"

const ( 
   p, q, r = iota, iota, iota 
)

func main() {
    fmt.Println(p, q, r)
}
A# 12. False.
Note: They have different outputs.
          Output of Ref12A
          0 1 2

          Output of Ref12B 
          0 0 0

Q# 13. What's the output of following code?

package main

import "fmt"

func main(){

     c := [...]int{} 

     fmt.Println(len(c))
 
}

A# 13 
    0

Note: Similarly, c := [...]int{4, 7, 2} would have given an output of 3. Remember, in an 
array declaration you've the option to replace length of the array with ... and Go run time
 is intelligent enough to compute the length at run time.

Q# 14. Arrays are value types i.e. in case of arrays as arguments, functions get their 
copies instead of a reference. True or False?

A# 14. True

Q# 15. Slices are reference type - the variable are stored in the heap? True or False?
A# 15. True
Q# 16. What's the output of following code?


package main

import "fmt"

func main() {
    
 oddSlc := []int{1,3,5,7}     
 evenSlc := []int{2,4,6,8}
 copy(evenSlc, oddSlc[2:])    
 fmt.Println("evenSlc = ", evenSlc)
}

A# 16. 
evenSlc =  [5 7 6 8]

Q# 17. Maps are value types. True or False?
A# 17. False

Note: Maps are Reference types. 
Q# 18. Is it recommended to use Global Variables in a program that implements G
routines?
A# 18. Global variables are not recommended as they may get accessed by multiple go routines (threads) concurrently that can easily lead to an unexpected behavior causing arbitrary results. 

Q# 19. Which of the following is NOT a valid Go identifier?

           a. _score2016
           b. 2016_Score
           c. गगन
          d. गगनSky

P.S. Identifiers name program entities such as variables, functions, constants, 
structs, slices, maps etc.

A# 19.  b
Imp. NOTE: In Go the names of variable, function, constant, struct etc must begin with an Unicode letter or an underscore.
Q# 20. Is variable name iCount same as icount in Go programming?
A# 20. No. Go is case sensitive.


Q# 21. In idiomatic Go code package names are all in lower case. Do you agree?
A#  21. Yes. A few OS may not be able to handle mixed case names of packages.
Q# 22. renderHtml - is it an idiomatic Go variable name?

A# 22. No. renderHTML is a better choice. Andrew Gerrand suggestsAcronyms should be all capitals, as in ServeHTTP and IDProcessor.

Q# 23. In Go there's no concept of uninitialized variable. True or False?
A# 23. True
Q# 24. Which of the following is initial value (zero value) for interfaces, slice, pointers, 
maps, channels and functions?

                a. 0
                b. ""
                c. nil
                d. false

A# 24. c

Q# 25. A good name (say a variable name) in Go is short, consistent &amp; easy to understand. Keeping this context in mind, do you agree with the following rule of thumb is Go:
The greater the distance between a name declaration &amp; its uses, the longer the name
should be.

A# 25. Agree.

Q# 26. Is it True - Go compiler is bootstrapped - i.e. Go programming has been used to build Go compiler?

A# 26. Yes. Go 1.4 was used to build Go 1.5. As of Go 1.4 the Go compiler was writtem in C language.
Q# 27. What is the output of the following code snippet?
package main

import "fmt"

func main() {
 var i, j int
 fmt.Println(&i == &i, &i == &j, &j == nil)
}
A# 27. 

     true    false    false


Q# 28. What is the output of the following code snippet?
package main

import "fmt"

func main() {
 x := 1
 y := &x

 fmt.Println(*y)

 *y = 2
 fmt.Println(x)

}
A# 28. 
       1
       2
Q# 29. What is the output of the following code snippet?

package main

import "fmt"

func main() {

 x := 1
 incr(&x)
 fmt.Println(incr(&x))

}
func incr(p *int) int {
 *p++
 return *p
}

A# 29. 

          3

Q# 30. Arrays are homogeneous (their elements have same type) whereas Structs are heterogeneous. Is this Statement True?
 A# 30. Yes.

 
Q# 31. Arrays Structs are fixed size. In contrast Slices Maps are dynamic data structures that grow as values are added. Is this Statement True? 

 A# 31. Yes.


     
P.S. - This is a work in progress. Please contribute. Send your questions
to admin[at]techno-pulse[dot]com.