Saturday, September 4, 2021

GO Programming / Golang Interview Questions & Answers

 1) Explain what is GO?

GO is an open source programming language which makes it easy to build simple, reliable and efficient software. Programs are constructed from packages, whose properties allow efficient management of dependencies.

2) What is syntax like in GO?

Syntax in GO is specified using Extended Backus-Naur Form (EBNF)

  • Production = production_name “=” [ Expression ]
  • Expression = Alternative { “l” Alternative }
  • Alternative = Term { Term }
  • Term = Production_name l token [ “…”token] l Group l Option l Repetition
  • Group = “ ( “ Expression”)”
  • Option = “ [ “ Expression “ ]”
  • Repetition = “ {“ Expression “}”

3) Explain what is string literals?

A string literals represents a string constant obtained from concatenating a sequence of characters.

There are two forms,

  • Raw string literals: The value of raw string literals are character sequence between back quotes ‘‘.  The value of a string literal is the string composed of the uninterrupted character between quotes.
  • Interpreted string literals: It is represented between double quotes ““. The text between the double quotes which may not contain newlines, forms the value of the literal.

4) Explain packages in Go program?

Every GO program is made up of packages.  The program starts running in package main.  This program is using the packages with import paths “fmt” and “math/rand”.

5) Explain workspace in GO?

Inside a workspace GO code must be kept.  A workspace is a directory hierarchy with three directories at its root.

  • src contains GO source files organized into packages
  • pkg contains package objects and
  • bin contains executable commands

6) Explain how to use custom packages in GO language?

If you are making your library a separate go get –table project and if your library is for internal use then you can code like this

  • Under the directory of your project place the directory with library files
  • Refer to the library using its path relative to the root of your workspace consisting the project

For example,

src/

myproject/

mylib/

mylib.go

. . .

main.go

Now, in main.go you could import myprojec/mylib.

7) Explain what is GOPATH environment variable?

The GOPATH environment variable determines the location of the workspace. It is the only environment variable that you have to set when developing Go code.

8) Explain how you can do testing in GO?

It has a lightweight testing framework consists of the go test command and the testing package.

To write a test you have to create a file with a name ending in _testing. Go which contains functions named TestXXX with signature func (t *testing.T).  The test framework runs each such function.

9) Explain what is string types?

A string type represents the set of string values, and string values are sequence of bytes.  Strings once created is not possible to change.

10) What are the advantages of GO?

  • GO compiles very quickly
  • Go supports concurrency at the language level
  • Functions are first class objects in GO
  • GO has garbage collection
  • Strings and Maps are built into the language

11) List out the built in support in GO?

The available built-in-support in GO includes

  • Container: container/list , container/heap
  • Web Server: net/http
  • Cryptography: Crypto/md5 , crypto/sha1
  • Compression: compress/ gzip
  • Database: database/sql

12) Explain what is go routine in GO? How you can stop go routine?

A goroutine is a function which is capable of running concurrently with other functions

To stop goroutine, you pass the goroutine  a signal channel, that signal channel is used to push a value into when you want the goroutine to stop.  The goroutine polls that channel regularly as soon as it detects a signal, it quits.

13) Explain how you can write multiline strings in GO?

To write multiline string in GO you can use a raw string literal, where the string is delimited by back quotes rather than double quotes.

‘ line  1

line  2

line  3 ’

14) Explain how you to access command line arguments passed to a GO program?

You can access the command line argument using the os.Args variables. For example,

15) Explain how pointer is represented in GO?

In GO a pointer is represented by using the * (asterisk) character followed by the type of the stored value.

16) How you can format a string without printing?

To format a string without printing you have to use command

17) Explain how arrays in GO works differently then C ?

In GO Array works differently than it works in C

  • Arrays are values, assigning one array to another copies all the elements
  • If you pass an array to a function, it will receive a copy of the array, not a pointer to it
  • The size of an array is part of its type. The types [10] int and [20] int are distinct

18) Explain GO Interfaces ?

In GO, interfaces is a way to specify the behaviour of an object.  An interface is created by using the “type” word, followed by a name and the keyword interface.  An interface is specified as two things.

  • A set of methods
  • Also it is referred as type

19) Explain what Type assertion is used for and how it does it?

Type conversion is used to convert dissimilar types in GO.  A type  assertion takes an interface value and retrieve from it a value of the specified explicit type.

20) In GO language how you can check variable type at runtime?

A special type of switch is dedicated in GO to check variable type at runtime, this switch is referred as type switch.  Also, you can switch on the type of an interface value with Type Switch.

Questions on Golang Basics

 1. What are the benefits of using Go compared to other languages?

  • Unlike other languages which started as academic experiments, Go code is pragmatically designed. Every feature and syntax decision is engineered to make life easier for the programmer.

  • Golang is optimized for concurrency and works well at scale.

  • Golang is often considered more readable than other languages due to a single standard code format.

  • Automatic garbage collection is notably more efficient than Java or Python because it executes concurrently alongside the program.


2. What are string literals?

A string literal is a string constant formed by concatenating characters. The two forms of string literal are raw and interpreted string literals.

Raw string literals are written within backticks (foo) and are filled with uninterpreted UTF-8 characters. Interpreted string literals are what we commonly think of as strings, written within double quotes and containing any character except newline and unfinished double quotes.


3. What data types does Golang use?

Golang uses the following types:

  • Method
  • Boolean
  • Numeric
  • String
  • Array
  • Slice
  • Struct
  • Pointer
  • Function
  • Interface
  • Map
  • Channel

4. What are packages in a Go program?

Packages (pkg) are directories within your Go workspace that contain Go source files or other packages. Every function, variable, and type from your source files are stored in the linked package. Every Go source file belongs to a package, which is declared at the top of the file using:

package <packagename>

You can import and export packages to reuse exported functions or types using:

import <packagename>

Golang’s standard package is fmt, which contains formatting and printing functionalities like Println().


5. What form of type conversion does Go support? Convert an integer to a float.

Go supports explicit type conversion to satisfy its strict typing requirements.

:= 55      //int

:= 67.8    //float64

sum := i + int(j) //j is converted to int

6. What is a goroutine? How do you stop it?

goroutine is a function or method that executes concurrently alongside any other goroutines using a special goroutine thread. Goroutine threads are more lightweight than standard threads, with most Golang programs using thousands of goroutines at once.

To create a goroutine, add the go keyword before the function declaration.

go f(x, y, z)

You can stop a goroutine by sending it a signal channel. Goroutines can only respond to signals if told to check, so you’ll need to include checks in logical places such as at the top of your for loop.


7. How do you check a variable type at runtime?

The Type Switch is the best way to check a variable’s type at runtime. The Type Switch evaluates variables by type rather than value. Each Switch contains at least one case, which acts as a conditional statement, and a default case, which executes if none of the cases are true.

For example, you could create a Type Switch that checks if interface value i contains the type int or string:


8. How do you concatenate strings?

The easiest way to concatenate strings is to use the concatenation operator (+), which allows you to add strings as you would numerical values.


Intermediate Golang Questions


9. Explain the steps of testing with Golang.

Golang supports automated testing of packages with custom testing suites.

To create a new suite, create a file that ends with _test.go and includes a TestXxx function, where Xxx is replaced with the name of the feature you’re testing. For example, a function that tests login capabilities would be called TestLogin.

You then place the testing suite file in the same package as the file you wish to test. The test file will be skipped on regular execution but will run when you enter the go test command.


10. What are function closures?

Function closures is a function value that references variables from outside its body. The function may access and assign values to the referenced variables.

For example: adder() returns a closure, which is each bound to its own referenced sum variable.


11. How do we perform inheritance with Golang?

This is a bit of a trick question: there is no inheritance in Golang because it does not support classes.

However, you can mimic inheritance behavior using composition to use an existing struct object to define a starting behavior of a new object. Once the new object is created, functionality can be extended beyond the original struct.

type Animal struct {
    // …
}

func (*Animal) Eat()   { … }
func (*Animal) Sleep() { … }
func (*Animal) Run() { … }

type Dog struct {
    Animal
    // …
}

The Animal struct contains Eat()Sleep(), and Run() functions. These functions are embedded into the child struct Dog by simply listing the struct at the top of the implementation of Dog.


12. Explain Go interfaces. What are they and how do they work?

Interfaces are a special type in Go that define a set of method signatures but do not provide implementations. Values of interface type can hold any value that implements those methods.

Interfaces essentially act as placeholders for methods that will have multiple implementations based on what object is using it.

For example, you could implement a geometry interface that defines that all shapes that use this interface must have an implementation of area() and perim().

type geometry interface {
    area() float64
    perim() float64
}

13. What are Lvalue and Rvalue in Golang?

Lvalue

  • Refers to a memory location

  • Represents a variable identifier

  • Mutable

  • May appear on the left or right side of the = operator

For example: In the statement x =20x is an lvalue and 20 is an rvalue.

Rvalue

  • Represents a data value stored in memory

  • Represents a constant value

  • Always appears on the = operator’s right side.

For example, The statement 10 = 20 is invalid because there is an rvalue (10) left of the = operator.


14. What are the looping constructs in Go?

Go has only one looping construct: the for loop. The for loop has 3 components separated by semicolons:

  • The Init statement, which is executed before the loop begins. It’s often a variable declaration only visible within the scope of the for loop.

  • The condition expression, which is evaluated as a Boolean before each iteration to determine if the loop should continue.

  • The post statement, which is executed at the end of each iteration.


15. Can you return multiple values from a function?

Yes. A Go function can return multiple values, each separated by commas in the return statement.


Coding challenges with Golang


16. Implement a Stack (LIFO)

Implement a stack structure with pop, append, and print top functionalities.

Solution

You can implement a stack using a slice object.

First, we use the built-in append() function to implement the append behavior. Then we use len(stack)-1 to select the top of the stack and print.

For pop, we set the new length of the stack to the position of the printed top value, len(stack)-1.


17. Print all permutations of a slice characters or string

Implement the perm() function that accepts a slice or string and prints all possible combinations of characters.

Solution

We use rune types to handle both slices and strings. Runes are Unicode code points and can therefore parse strings and slices equally.


18. Swap the values of two variables without a temporary variable

Implement swap() which swaps the value of two variables without using a third variable.

Solution

While this may be tricky in other languages, Go makes it easy.

We can simply include the statement b, a = a, b, what data the variable references without engaging with either value.


19. Implement min and max behavior

Implement Min(x, y int) and Max(x, y int) functions that take two integers and return the lesser or greater value, respectively.

Solution

By default, Go only supports min and max for floats using math.min and math.max. You’ll have to create your own implementations to make it work for integers.


20. Reverse the order of a slice

Implement function reverse that takes a slice of integers and reverses the slice in place without using a temporary slice.

Solution

Our for loop swaps the values of each element in the slice will slide from left to right. Eventually, all elements will be reversed.


21. What is the easiest way to check if a slice is empty?

Create a program that checks if a slice is empty. Find the simplest solution.

Solution

The easiest way to check if a slice is empty is to use the built-in len() function, which returns the length of a slice. If len(slice) == 0, then you know the slice is empty.

For example:


22. Format a string without printing it

Find the easiest way to format a string with variables without printing the value.

Solution

The easiest way to format without printing is to use the fmt.Sprintf(), which returns a string without printing it.

For example:


Golang Concurrency Questions


23. Explain the difference between concurrent and parallelism in Golang

Concurrency is when your program can handle multiple tasks at once while parallelism is when your program can execute multiple tasks at once using multiple processors.

In other words, concurrency is a property of a program that allows you to have multiple tasks in progress at the same time, but not necessarily executing at the same time. Parallelism is a runtime property where two or more tasks are executed at the same time.

Parallelism can therefore be a means to achieve the property of concurrency, but it is just one of many means available to you.

The key tools for concurrency in Golang are goroutines and channels. Goroutines are concurrent lightweight threads while channels allow goroutines to communicate with each other during execution.


24. Merge Sort

Implement a concurrent Merge Sort solution using goroutines and channels.

You can use this sequential Merge Sort implementation as a starting point:

Solution

Firstly, in merge sort, we keep dividing our array recursively into the right side and the left side and call the MergeSort function on both sides from line 30 to line 34.

Now we have to make sure that Merge(left,right) is executed after we get return values from both the recursive calls, i.e. both the left and right must be updated before Merge(left,right) can be executable. Hence, we introduce a channel of type bool on line 26 and send true on it as soon as left = MergeSort(data[:mid]) is executed (line 32).

The <-done operation blocks the code on line 35 before the statement Merge(left,right) so that it does not proceed until our goroutine has finished. After the goroutine has finished and we receive true on the done channel, the code proceeds forward to Merge(left,right) statement on line 36.


25. Sum of Squares

Implement the SumOfSquares function which takes an integer, c and returns the sum of all squares between 1 and c. You’ll need to use select statements, goroutines, and channels.

For example, entering 5 would return 55 because 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55

You can use the following code as a starting point:

Solution

Take a look at our SumOfSquares function. First, on line 4, we declare a variable y and then jump to the For-Select loop. We have two cases in our select statements:

  • case c <- (y*y): This is to send the square of y through the channel c, which is received in the goroutine created in the main routine.

  • case <-quit: This is to receive a message from the main routine that will return from the function.

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...