1) What is Go programming language?
GO is an open source programming language developed at Google. It is also known as Golang. This language is designed primarily for system programming.
2) Why should one use Go programming language?
Because Go is an open source programming language so, it is very easy to build simple, reliable and efficient software.
3) Who is known as the father of Go programming language?
Go programming language is designed by Robert Griesemer, Rob Pike, and Ken Thompson. It is developed at Google Inc. in 2009.
4) What are packages in Go program?
Go programs are 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) Does Go support generic programming?
Go programming language doesn’t provide support for generic programming.
6) Is Go a case sensitive language?
Yes! Go is a case sensitive programming language.
7) What is a string literal in Go programming?
A string literals specifies a string constant that is obtained from concatenating a sequence of characters.
There are two types of string literals:
Raw string literals: The value of raw string literals are character sequence between back quotes “. Its value is specified as a string literal that composed of the uninterrupted character between quotes.
Interpreted string literals: It is shown between double quotes ” “. The value of the literal is specified as text between the double quotes which may not contain newlines.
8) What is workspace in Go?
A workspace contains Go code. A workspace is a directory hierarchy with three directories at its root.
“src” directory contains GO source files organized into packages.
“pkg” directory contains package objects.
“bin” directory contains executable commands
9) What is the default value of type bool in Go programming?
“false” is the default value of type “bool”.
10) What is GOPATH environment variable in go programming?
The GOPATH environment variable specifies the location of the workspace. You must have to set this environment variable while developing Go code.
11) What are the advantages/ benefits of Go programming language?
Advantages/ Benefits of Go programming language:
Go is fast and compiles very quickly.
It supports concurrency at the language level.
It has Garbage collection.
It supports various safety features and CSP-style concurrent programming features.
Strings and Maps are built into the language.
Functions are first class objects in this language.
12) What are the several built-in supports in Go?
A list of built-in supports in Go:
Container: container/list,container/heap
Web Server: net/http
Cryptography: Crypto/md5 ,crypto/sha1
Compression: compress/ gzip
Database: database/sql
13) What is goroutine in Go programming language?
A goroutine is a function which usually runs concurrently with other functions. If you want to stop goroutine, you pass a signal channel to the goroutine, that signal channel pushes 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.
_______________________________________
Quit : = make (chan bool) go func ( ) { for { select { case <- quit: return default // do other stuff } } }() // Do stuff // Quit goroutine Quit <- true _______________________________
14) How to write multiple strings in Go programming?
To write multiple strings in Go, you should use a raw string literal, where the string is delimited by back quotes.
For example:
_________________
'line 1 line 2 line 3 ' _____________
15) What is the usage of break statement in Go programming language?
The break statement is used to terminate the for loop or switch statement and transfer execution to the statement immediately following the for loop or switch.
16) What is the usage of continue statement in Go programming language?
The continue statement facilitates the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
17) What is the usage of goto statement in Go programming language?
The goto statement is used to transfer control to the labeled statement.
18) Explain the syntax for ‘for’ loop.
The syntax of a for loop in Go programming language is:
_________________________________________________
for [condition | ( init; condition; increment ) | Range]
{
statement(s);
}
__________________________________________________
19) Write the syntax to create a function in Go programming language?
Syntax to create a function in Go:
__________________________________________________________
func function_name( [parameter list] ) [return_types]
{
body of the function
}
____________________________________________________________
20) Explain static type declaration of variable in Go programming language?
Static type variable declaration is used to provide assurance to the compiler that there is one variable in the given type and name so that there is no need for compiler to know complete detail about the variable for further processing. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable declaration at the time of linking of the program.
21) Explain dynamic type declaration of a variable in Go programming language?
A dynamic type variable declaration needs a compiler to interpret the type of variable according to the value passed to it. Compilers don’t need a variable to have type statically as a necessary requirement.
22) How would you print type of variable in Go?
You have to use the following code to print the type of a variable:
Formula –
var a, b, c = 3, 4, “foo”
fmt.Printf(“a is of type %T\n”, a)
23) What is a pointer in Go?
A pointer is used to hold the address of a variable.
For example:
_______________________________
var x = 5 var p *int p = &x fmt.Printf("x = %d", *p) ________________________
Here x can be accessed by *p.
24) How a pointer is represented in Go?
In Go, a pointer is represented by using the *(asterisk) character followed by the type of the stored value.
25) Is it true that short variable declaration := can be used only inside a function?
Yes. A short variable declaration := can be used only inside a function.
26) 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.
27) What data types does Golang use?
Golang uses the following types:
Method
Boolean
Numeric
String
Array
Slice
Struct
Pointer
Function
Interface
Map
Channel
28) 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.
_________________________________________
<!-- wp:paragraph -->
<p>i := 55 //int</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>j := 67.8 //float64</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>sum := i + int(j) //j is converted to int</p>
<!-- /wp:paragraph -->
____________________________________________
29) 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.
____________________________________________________________
<!-- wp:paragraph -->
<p>package main<br>import "fmt"</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>func main() {</p>
<!-- /wp:paragraph -->
<!-- wp:code -->
<pre class="wp-block-code"><code>// Creating and initializing strings
// using var keyword
var str1 string
str1 = "Hello "
var str2 string
str2 = "Reader!"
// Concatenating strings
// Using + operator
fmt.Println("New string 1: ", str1+str2)
// Creating and initializing strings
// Using shorthand declaration
str3 := "Welcome"</code></pre>
<!-- /wp:code -->
<!-- wp:paragraph -->
<p>str4 := "Educative.io"</p>
<!-- /wp:paragraph -->
<!-- wp:code -->
<pre class="wp-block-code"><code>// Concatenating strings
// Using + operator
result := str3 + " to " + str4
fmt.Println("New string 2: ", result) </code></pre>
<!-- /wp:code -->
<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->
________________________________________________________
30) 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.
31) 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.
________________________________________________________________________
<!-- wp:paragraph -->
<p>package main</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>import "fmt"</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>func adder() func(int) int {<br>sum := 0<br>return func(x int) int {<br>sum += x<br>return sum<br>}<br>}</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>func main() {<br>pos, neg := adder(), adder()<br>for i := 0; i < 10; i++ {<br>fmt.Println(<br>pos(i),<br>neg(-2*i),<br>)<br>}<br>}</p>
<!-- /wp:paragraph -->
__________________________________________________
32) What do you understand by Golang string literals?
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:
Raw string literals: Here, the values are uninterrupted character sequences between backquotes. For example:
__________________________________
interviewbit
____________________________
Interpreted string literals: Here, the character sequences are enclosed in double quotes. The value may or may not have new lines. For example:
_______________________________
"Interviewbit Website" ________________________
33) What is the syntax used for the for loop in Golang? Explain
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:
- The init steps gets executed first. This is executed only once at the beginning of the loop. This is done for declaring and initializing the loop control variables. This field is optional as long as we have initialized the loop control variables before. If we are not doing anything here, the semicolon needs to be present.
- The condition is then evaluated. If the condition is satisfied, the loop body is executed.
*If the condition is not satisfied, the control flow goes to the next statement after the for loop.
*If the condition is satisfied and the loop body is executed, then the control goes back to the increment statement which updated the loop control variables. The condition is evaluated again and the process repeats until the condition becomes false.
If the Range is mentioned, then the loop is executed for each item in that Range.
Consider an example for for loop. The following code prints numbers from 1 to 5.
____________________________________
<!-- wp:paragraph -->
<p>package main</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>import "fmt"</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>func main() {<br>// For loop to print numbers from 1 to 5<br>for j := 1; j <= 5; j++ {<br>fmt.Println(j)<br>}</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->
________________________________
The output of this code is:
1
2
3
4
5
34) What is “slice” in Go?
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:
Pointer: This is used for pointing to the first element of the array accessible via slice. The element doesn’t need to be the first element of the array.
Length: This is used for representing the total elements count present in the slice.
Capacity: This represents the capacity up to which the slice can expand.
For example: Consider an array of name arr having the values “This”,“is”, “a”,“Go”,“interview”,“question”.
_________________________________________________________________________________
<!-- wp:paragraph -->
<p>package main</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>import "fmt"</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p>func main() {</p>
<!-- /wp:paragraph -->
<!-- wp:code -->
<pre class="wp-block-code"><code>// 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))</code></pre>
<!-- /wp:code -->
<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->
__________________________________________________________________
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: 3 The capacity of the slice: 5 ___________________________________________
35) Why is Golang fast compared to other languages?
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.
36) How can we check if the Go map contains a key?
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.
37) Can you format a string without printing?
Yes, we can do that by using the Sprintf command as shown in the example below:
return fmt.Sprintf (“Size: %d MB.”, 50)
The fmt.Sprintf function formats a string and returns the string without printing it
38) What do you understand by Type Assertion in Go?
The type assertion takes the interface value and retrieves the value of the specified explicit data type. The syntax of Type Assertion is:
________________
t := i.(T) ____________
Here, the statement asserts that the interface value i has the concrete type T and assigns the value of type T to the variable t. In case i does not have concrete type T, then the statement will result in panic.
For testing, if an interface has the concrete type, we can do it by making use of two values returned by type assertion. One value is the underlying value and the other is a bool value that tells if the assertion is completed or not. The syntax would be:
_______________________________
t, isSuccess := i.(T) ________________________
Here, if the interface value i have T, then the underlying value will be assigned to t and the value of isSuccess becomes true. Else, the isSuccess statement would be false and the value of t would have the zero value corresponding to type T. This ensures there is no panic if the assertion fails.
39) How will you check the type of a variable at runtime in Go?
In Go, we can use a special type of switch for checking the variable type at runtime. This switch statement is called a “type switch”.
Consider the following piece of code where we are checking for the type of variable v and performing some set of operations.
_____________________________
switch v := param.(type) { default: fmt.Printf("Unexpected type %T", v) case uint64: fmt.Println("Integer type") case string: fmt.Println("String type") } __________________________
In the above code, we are checking for the type of variable v, if the type of variable is uint64, then the code prints “Integer type”. If the type of variable is a string, the code prints “String type”. If the type doesn’t match, the default block is executed and it runs the statements in the default block.
40) Which is safer for concurrent data access? Channels or Maps?
Channels are safe for concurrent access because they have blocking/locking mechanisms that do not let goroutines share memory in the presence of multiple threads.
Maps are unsafe because they do not have locking mechanisms. While using maps, we have to use explicit locking mechanisms like mutex for safely sending data through goroutines
41) 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.
42) Do you need both GOPATH and GOROOT variables, and why?
Most of the time, you do not need them both. You need only the GOPATH variable set pointing to the Go packages tree or trees.
GOROOT points to the root of the Go language home directory, but it is most probably already set to the directory of the current Go language installation. It is easy to check whether it is so with the go env command:
______________________________________
$ go env … GOROOT=“/home/zabb/go” … ______________________________
It is necessary to set the GOROOT variable if there are multiple Go language versions on the same system or if the Go language has been downloaded as a binary package taken from the internet or transferred from another system.
43) Write a Go program to swap variables in a list?
Consider we have num1=2, num2=3. To swap these two numbers, we can just write: num1,num2 = num2, num1
The same logic can be extended to a list of variables as shown below:
________________________________________________________________________________
package main
import "fmt"
func swapContents(listObj []int) {
for i, j := 0, len(listObj)-1; i < j; i, j = i+1, j-1 {
listObj[i], listObj[j] = listObj[j], listObj[i]
}
}
func main() {
listObj := []int{1, 2, 3}
swapContents(listObj)
fmt.Println(listObj)
}
_____________________________________________________________
The code results in the output:
[3 2 1]
44) Does Go programming language support operator overloading?
Go programming language doesn’t provide support for operator overloading.
45) Does Go support method overloading?
Go programming language doesn’t provide support for method overloading.
46) Does Go support pointer arithmetics?
Go programming language doesn’t provide support for pointer arithmetic.
47) What is Type assertion in Go? What does it do?
A type assertion takes an interface value and retrieves from it a value of the specified explicit type.
Type conversion is used to convert dissimilar types in GO.
48) What are the different methods in Go programming language?
In Go programming language there are several different types of functions called methods. In method declaration syntax, a “receiver” is used to to represent the container of the function. This receiver can be used to call function using “.” operator.
49) What is the default value of a local variable in Go?
The default value of a local variable is as its corresponding 0 value.
50) 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.
- Best AI tools for Software Engineers - November 4, 2024
- Installing Jupyter: Get up and running on your computer - November 2, 2024
- An Introduction of SymOps by SymOps.com - October 30, 2024