22.8.15

Golang pop quiz

I find myself using Vim for Golang code, and that means - you need to be good at catching errors by eye.  So here are some Go questions that will keep you sharp if you find yourself forgetting minutia.


EASY QUESTIONS

0) Does this code compile, if so, whats the output?  If not, where is the error message.

nope !  y is undeclared.
nope again ! no new variables on the left side of the second x := statement.

1) How long does this program take to run (approximately, assuming print statements take 0 nanoseconds).

Go's time is default nanoseconds.  So this runs in ~ 5 nano seconds assuming the other statements have negligible time.  If you want to make it run for 5 seconds, you would multiple time.Duration by time.Second.



2) The following code deadlocks.  Why? Fix the following code, in a minimal number of lines, so that "wait1" writes to the "c" channel after 5 nanoseconds without deadlocking.

The reason is that the channel blocks on write, and nobody is attached to the other end !All you have to do here is add a go routine which surrounds the time.Sleep phrase. (go func(){ time.Sleep(...)} () 

INTERMEDIATE QUESTIONS

1) Whats wrong with the reference to the LeaseUser type in the code below?

Golang packages don't use fully qualified names for things in the same package!  Since you're not importing "ha", you don't need to reference it by the package name.



More coming soon...

No comments:

Post a Comment