This section includes 7 InterviewSolutions, each offering curated multiple-choice questions to sharpen your Current Affairs knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
What are Go channels and how are channels used in Golang? |
|
Answer» Go channel is a medium using which goroutines communicate DATA values with each other. It is a technique that allows data transfer to other goroutines. A channel can transfer data of the same type. The data transfer in the channel is bidirectional meaning the goroutines can use the same channel for sending or receiving the data as shown in the image below: A channel can be created by adding the chan keyword as shown in the SYNTAX below: VAR channel_name chan TypeIt can also be created by using the make() FUNCTION as: channel_name:= make(chan Type)To send the data to a channel, we can use the <- operator as shown in the syntax: channel_name <- elementTo receive data sent by the send operator, we can use the below syntax: element := <-Mychannel |
|
| 2. |
How can we check if the Go map contains a key? |
|
Answer» A MAP, in general, is a collection of elements grouped in KEY-value pairs. One key refers to one value. Maps provide FASTER access in terms of O(1) COMPLEXITY to the values if the key is known. A map is visualized as shown in the image below: Once the values are stored in key-value pairs in the map, we can retrieve the object by using the key as map_name[key_name] and we can check if the key, say “foo”, is present or not and then perform some operations by using the below code: if val, isExists := map_obj["foo"]; isExists { //do steps needed here}From the above code, we can see that two variables are being initialized. The val variable would get the value corresponding to the key “foo” from the map. If no value is present, we get “zero value” and the other variable isExists will get a bool value that will be SET to true if the key “foo” is present in the map else false. Then the isExists condition is evaluated, if the value is true, then the body of the if would be executed. |
|
| 3. |
Why is Golang fast compared to other languages? |
|
Answer» Golang is faster than other programming languages because of its simple and efficient memory management and concurrency model. The compilation process to MACHINE code is very fast and efficient. Additionally, the dependencies are linked to a SINGLE BINARY FILE thereby putting off dependencies on SERVERS. |
|
| 4. |
What are Go Interfaces? |
|
Answer» Go interfaces are those that have a defined set of method signatures. It is a custom type who can take values that has these methods implementation. The interfaces are abstract which is why we cannot create its instance. But we can create a variable of type interface and that variable can then be assigned to a concrete value that has methods required by the interface. Due to these reasons, an interface can act as two things:
They are created by USING the type keyword followed by the name needed for the interface and finally followed by the keyword interface. The syntax goes as follows: type name_of_interface interface{// Method signatures}Consider an example of creating an interface of the name “golangInterfaceDemo” having two methods demo_func1() and demo_func2(). The interface will be defined as: // Create an interfacetype golangInterfaceDemo interface{ // Methods demo_func1() int demo_func2() float64}Interface also promotes abstraction. In Golang, we can use interfaces for creating common abstractions which can be used by multiple types by defining method declarations that are compatible with the interface. Conside the following example: package main import "fmt" // "Triangle" data typetype Triangle struct { base, height float32} // "Square" data typetype Square struct { length float32} // "Rectangle" data typetype Rectangle struct { length, breadth float32} // To calculate area of trianglefunc (triangle Triangle) Area() float32 { return 0.5 * triangle.base * triangle.height} // To calculate area of squarefunc (square Square) Area() float32 { return square.length * square.length} // To calculate area of rectanglefunc (rect Rectangle) Area() float32 { return rect.length * rect.breadth} // Area interface for achieving abstractiontype Area interface { Area() float32} func main() { // Declare and assign values to varaibles triangleObject := Triangle{base: 20, height: 10} squareobject := Square{length: 25} rectObject := Rectangle{length: 15, breadth: 20} // Define a variable of type interface var shapeObject Area // Assign to "Triangle" type variable to the Area interface shapeObject = triangleObject fmt.Println("Triangle Area = ", shapeObject.Area()) // Assign to "Square" type variable to the Area interface shapeObject = squareobject fmt.Println("Square Area = ", shapeObject.Area()) // Assign to "Rectangle" type variable to the Area interface shapeObject = rectObject fmt.Println("Rectangle Area = ", shapeObject.Area())}In the above example, we have created 3 types for the shapes triangle, square and rectangle. We have also defined 3 Area() functions that calculate the area of the shapes based on the input object type PASSED. We have also defined an interface NAMED Area and we have defined the method signature Area() within it. In the main function, we are creating the objects, assigning each object to the interface and calculating the area by calling the method declared in the interface. Here, we need not know specifically about the function that needs to be called. The interface method will take care of this considering the object type. This is called abstraction. The output of the above code will be: Triangle Area = 100Square Area = 625Rectangle Area = 300 |
|
| 5. |
What is “slice” in Go? |
|
Answer» Slice in Go is a lightweight data structure of variable length sequence for STORING homogeneous data. It is more convenient, powerful and flexible than an array in Go. Slice has 3 components:
For example: Consider an array of NAME arr having the values “This”,“is”, “a”,“Go”,“interview”,“question”. package main import "fmt" func main() { // Creating an array arr := [6]string{"This","is", "a","Go","interview","question"} // Print array fmt.Println("Original Array:", arr) // Create a slice slicedArr := arr[1:4] // Display slice fmt.Println("Sliced Array:", slicedArr) // Length of slice calculated using len() fmt.Println("Length of the slice: %d", len(slicedArr)) // Capacity of slice calculated using cap() fmt.Println("Capacity of the slice: %d", cap(slicedArr))}Here, we are trying to slice the array to get only the first 3 words starting from the word at the first index from the original array. Then we are FINDING the length of the slice and the capacity of the slice. The output of the above code WOULD be: Original Array: [This is a Go interview question ]Sliced Array: [is a Go]Length of the slice: 3The capacity of the slice: 5The same is illustrated in the diagram below: |
|
| 6. |
Is it possible to declare variables of different types in a single line of code in Golang? |
|
Answer» Yes, this can be achieved by writing as SHOWN below: var a,B,C= 9, 7.1, "interviewbit"Here, we are assigning VALUES of a type Integer NUMBER, Floating-Point number and string to the three variables in a single line of code. |
|
| 7. |
Is it possible to return multiple values from a function in Go? |
|
Answer» Yes. Multiple values can be returned in Golang by sending comma-separated values with the return statement and by ASSIGNING it to multiple variables in a single statement as shown in the example below: package mainimport ( "FMT")func reverseValues(a,b string)(string, string){ return b,a //notice how multiple values are returned}func main(){ val1,VAL2:= reverseValues("interview","bit") // notice how multiple values are assigned fmt.Println(val1, val2)}In the above example, we have a FUNCTION reverseValues which simply returns the INPUTS in reverse order. In the main goroutine, we call the reverseValues function and the values are assigned to values val1 and val2 in one statement. The output of the code would be bit interview |
|
| 8. |
What do you understand by goroutine in Golang? |
|
Answer» A goroutine is nothing but a function in Golang that usually RUNS concurrently or parallelly with other functions. They can be imagined as a lightweight thread that has independent execution and can RUN concurrently with other routines. Goroutines are ENTIRELY managed by Go Runtime. Goroutines help Golang achieve concurrency.
In this code, we see that the sampleRoutine() function is called by specifying the keyword go before it. When a function is called a goroutine, the call will be returned immediately to the next line of the program STATEMENT which is why “Started Main” WOULD be printed first and the goroutine will be scheduled and run concurrently in the background. The sleep statement ensures that the goroutine is scheduled before the completion of the main goroutine. The output of this code would be: Started MainInside Sample GoroutineFinished Main |
|
| 9. |
What do you understand by the scope of variables in Go? |
|
Answer» The variable scope is DEFINED as the part of the program where the variable can be accessed. EVERY variable is statically scoped (meaning a variable scope can be identified at compile time) in Go which means that the scope is declared at the time of compilation itself. There are two scopes in Go, they are: |
|
| 10. |
What is the syntax used for the for loop in Golang? Explain. |
|
Answer» Go language follows the below syntax for implementing for loop. for [condition | ( init; condition; increment ) | Range] { statement(s); //more statements}The for loop works as follows:
Consider an EXAMPLE for for loop. The following code prints numbers from 1 to 5. package mainimport "fmt"func main() { // For loop to print numbers from 1 to 5 for j := 1; j <= 5; j++ { fmt.Println(j) }}The output of this code is: 12345 |
|
| 11. |
What do you understand by Golang string literals? |
|
Answer» String literals are those variables STORING string constants that can be a single CHARACTER or that can be obtained as a result of the CONCATENATION of a sequence of characters. GO provides two types of string literals. They are:
|
|
| 12. |
What are Golang pointers? |
|
Answer» Go Pointers are those variables that hold the address of any variables. Due to this, they are called SPECIAL variables. Pointers support two operators:
This is illustrated in the diagram below. Here, consider we have a variable x assigned to 100. We store x in the memory address 0x0201. Now, when we create a pointer of the name Y for the variable x, we assign the value as &x for storing the address of variable x. The pointer variable is stored in address 0x0208. Now to get the value stored in the address that is stored in the pointer, we can just write int Z:= *Y Pointers are used for the following purposes:
|
|
| 14. |
What are Golang packages? |
|
Answer» Go Packages (in short PKG) are nothing but directories in the Go workspace that contains Go source files or other Go packages themselves. Every single PIECE of code starting from variables to functions are written in the source files are in turn stored in a linked package. Every source file should belong to a package. From the image below, we can SEE that a Go Package is represented as a box where we can store multiple Go source files of the .go extension. We can also store Go packages as well within a package. The package is declared at the top of the Go source file as package <package_name> The packages can be imported to our source file by writing: IMPORT <package_name> An example of the Go package is fmt. This is a standard Go Package that has formatting and printing functionalities such as Println(). |
|
| 15. |
Why should one learn Golang? What are the advantages of Golang over other languages? |
|
Answer» Go LANGUAGE follows the principle of maximum EFFECT with minimum efforts. Every feature and syntax of Go was developed to ease the life of programmers. Following are the advantages of Go Language:
|
|
| 16. |
What is Golang? |
Answer»
|
|